createUploader()
createUploader is a function that simplifies file uploads for users.
Here is an example for uploading a file:
Frontend:
import { createUploader } from '@magicjs.dev/frontend';
import uploadServer from "./upload.server";
// The backend server function for handling file uploads
const { addFiles, upload, readyToUpload, uploadProgress, loading } = createUploader(uploadServer);
const handleUploadFile = () => {
upload();
};
return (
<div>
<input
type='file'
onChange={(e) => {
addFiles(e.target.files);
// Adds selected files to the uploader instance
}}
/>
<button
onClick={handleUploadFile}
disabled={Boolean(readyToUpload) === false || loading === true}
>
{/* readyToUpload is a boolean variable; it becomes true if any images are selected,
and false if none are chosen.
The boolean variable loading becomes true while the API is in progress and turns false once the operation is complete. */}
Upload
</button>
<div>{uploadProgress}</div>
{/* The numeric variable uploadProgress indicates the progress of the upload,
providing visibility into the ongoing upload process. */}
</div>
);
Backend upload.server
upload.server
import { createBackendFunction, createRequestContext, useFunctionContext, utils } from '@magicjs.dev/backend';
export default createBackendFunction(async function () {
createRequestContext(this)
.uploader()
.onFile((info, file) => {
// Will get the file information from the parameter info.
utils.saveFileToUserUploads('/upload-path', 'imageName.jpeg', file);
});
})
Last updated