Building a web app (Whinst) Part 17: Setting up file upload functionality

Building Whinst

The ability to upload files such as images and videos is an essential feature in most web and mobile apps, Whinst is no exception. In fact, images and videos are core to the Whinst web app. In this article, I’ll walk you through how I set up file upload functionality.

File upload functionality🗂

I set up file upload functionality in two parts. The first part was on the backend and the second part was on the frontend.

The first part: The first part involved creating a URL or API endpoint that will be used to save a file to a folder on the backend, setting up middleware used to save these files and creating a folder that will hold these saved files. For the API endpoint, I used one that was already made since file uploads in the app happen under an object that has other fields with different data types. It was just a matter of adding middleware to the endpoint to facilitate file uploads. I used a popular Nodejs middleware called Multer, which simplifies the otherwise complicated process of uploading files. Using Multer I set properties for the file such as its destination and the name it should be saved as. When a user clicks and activates the url Multer will save the file in the specified folder with the correct given name. The code below shows how Multer can be used to save files in a folder.

const multer = require('multer')

const storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, __dirname + '/uploads');
    },
    // Sets file(s) to be saved in uploads folder in same directory
    filename: function (req, file, callback) {
        callback(null, file.originalname);
    }
    // Sets saved filename(s) to be original filename(s)
  })
  
// Set saved storage options:
const upload = multer({ storage: storage })

app.post("/api", upload.array("files"), (req, res) => {
// Sets multer to intercept files named "files" on uploaded form data
    console.log(req.body); // Logs form body values
    console.log(req.files); // Logs any files
    res.json({ message: "File(s) uploaded successfully" });

});

The second part: The second part involved setting up functionality to get files from the computer file library and send the files to the backend using the API endpoint mentioned in the first part. To get files from the computer file library I used a simple input tag of type file. Using an event handler this file is then stored in state and sent to the backend via the API endpoint. For the file upload middleware on the backend to work correctly the file needs to be sent as a form object. To do this I used the FormData() constructor. The code below shows how a file can be uploaded and sent to the backend using a form object.

export default sendingFilesToBackend(){
const [file,setFile] = useState('');

 const sendFile = async()=>{
        const formData = new FormData()
        formData.append('file',file)
        await fetch('http://localhost:5000/api/',{
            method:'POST',
            body:formData,
        }).then((data=>data.json()))}

const handleFile=(e)=>{setFile(e.target.files[0])}

return(
 <input type='file' name='file' onChange={handleFile}/>

)
}

With the uploading of files now complete I’ve since moved on to set up functionality to display these media files on the frontend for users to see, something I’ll write about so stay tuned. Thank you for reading🙏.

Share

Leave a Comment

Your email address will not be published. Required fields are marked *