reactjsimagefile-upload

How to upload images from front-end to public folder in React


I want to be able to upload images to the ReactJS public folder straight from the front-end on both development and production. For production I am using heroku app with a nodejs backend.

From all the tutorials I have found online for uploading images with ReactJS they all use server-side to upload them to a cloud but I am wondering if it is possible to just upload them to the public folder like Lavarel does and if there are any drawbacks doing so?


Solution

  • The file just needs to be sent through an endpoint and on the NodeJS server deal with it like this. This server uploads the image file to public/uploads folder of the ReactJS client. Then in the response returns the file name and file path.

    app.post('/upload', (req, res) => {
      if (req.files === null) {
      return res.status(400).json({ msg: 'No file uploaded' });
      }
    
      const file = req.files.file;
    
      file.mv(`${__dirname}/client/public/uploads/${file.name}`, err => {
        if (err) {
          console.error(err);
          return res.status(500).send(err);
        }
    
        res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
      });
    });