Handling file uploads and downloads
In this guide, we will learn how to upload and view a file.
Setting up Backend
Upload File
Create a '
Blank Backend Function
' file inmain-features
folder and name it as 'upload
'.Paste the below code in '
upload.server.tsx
'
It calls the
uploader
method on the request context, which sets up functionality related to handling file uploads.The
onFile
method is called, which sets up an event handler for when a file is uploaded. It takes a callback function(info, file)
as an argument.info
contains information about the uploaded file.file
contains the uploaded file itself.It uses the
utils.saveFileToUserUploads
function 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
'
The
readFileFromUserUploads
method from theutils
module 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
readFileFromUserUploads
operation, 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
'.
It renders a file input (
Input
) and a button (Button
) for file selection and upload, respectively.The
onChange
event of the file input adds selected files to the uploader instance using theaddFiles
function.The upload button is disabled if the
loading
state istrue
orreadyToUpload
isfalse
.It displays upload progress using the
uploadProgress
state.It renders an image tag (
img
) with the source URL obtained fromfileSrc.getLink("image.jpg")
, displaying a preview of the uploaded file.
Choose a file to upload and click on the button 'Upload
'. Refresh the page to view 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