Handling file uploads and downloads
In this guide, we will learn how to upload and view a file.
Stuck on Your Project? We've Got You Covered!
Whether you're short on time or need coding expertise, our Professional Services team is here to help.
Fast turnaround times
Expert developers
Affordable rates
Setting up Backend
Upload File
Create a '
Blank Backend Function' file inmain-featuresfolder and name it as 'upload'.Paste the below code in '
upload.server.tsx'
import {
createBackendFunction,
createRequestContext,
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("/", `image.jpg`, file)
})
})It calls the
uploadermethod on the request context, which sets up functionality related to handling file uploads.The
onFilemethod is called, which sets up an event handler for when a file is uploaded. It takes a callback function(info, file)as an argument.infocontains information about the uploaded file.filecontains the uploaded file itself.It uses the
utils.saveFileToUserUploadsfunction to save the uploaded file to a specified location in the user's uploads directory.
This code defines a backend function that handles file uploads. It uses the createRequestContext function to create a request context, sets up an uploader, and defines an event handler for handling file uploads.
Read File
Create a '
Blank Backend Function' file and name it as 'getfile'.Paste the below code in '
getfile.server.tsx'
import { createBackendFunction, utils } from "@magicjs.dev/backend"
export default createBackendFunction(async function (fileName: string) {
return utils.readFileFromUserUploads("/", fileName)
})The
readFileFromUserUploadsmethod from theutilsmodule is called with two arguments:"/": This is the path to the user's upload folder.fileName: This is the name of the file that needs to be read from the specified upload folder.
The function returns the result of the
readFileFromUserUploadsoperation, which represents the content or data of the file being read.
Integrate in UI
Create a '
Blank UI Component' file in a feature.Name the file '
upload' and give a suitable path. We are assigning the path: '/upload'.Paste the code given below in '
upload.tsx'.
import React from "react"
import { createUploader, createSrc } from "@magicjs.dev/frontend"
import { Button, Input } from "antd"
import uploadServer from "./upload.server"
import getfileServer from "./getfile.server"
const fileSrc = createSrc(getfileServer)
export default function Component(props: any) {
const { addFiles, upload, readyToUpload, uploadProgress, loading } =
createUploader(uploadServer)
return (
<div>
<Input
type="file"
onChange={(e) => {
addFiles(e.target.files)
// Adds selected files to the uploader instance
}}
/>
<Button
onClick={() => upload()}
disabled={loading === true || Boolean(readyToUpload) === false}
>
Upload: {uploadProgress}%
</Button>
<div>
<img src={fileSrc.getLink("image.jpg")} alt="File Preview" />
</div>
</div>
)
}It renders a file input (
Input) and a button (Button) for file selection and upload, respectively.The
onChangeevent of the file input adds selected files to the uploader instance using theaddFilesfunction.The upload button is disabled if the
loadingstate istrueorreadyToUploadisfalse.It displays upload progress using the
uploadProgressstate.It renders an image tag (
img) with the source URL obtained fromfileSrc.getLink("image.jpg"), displaying a preview of the uploaded file.

Ready to step into the role of a Product Owner?
Dive into our comprehensive course designed to equip you with the skills and knowledge needed to excel. Click here to embark on your journey towards becoming a proficient product owner and unlocking exciting career opportunities!
Last updated