Search code examples
node.jsreactjsexpressfile-uploadmulter

uploading image from react frontend to express backend and displaying it back in the frontend


All I want to achieve is to upload the image in react frontend, save it in local public/images folder in backend and display the uploaded images back in frontend. So far I have managed to upload the files to backend. I cant figure out how to display the files in frontend. I want to make a get request to send the image files to frontend

express code: express code image

const express = require("express");
const multer = require("multer");
const cors = require("cors");

const app = express();


app.use(cors());
app.use(express.static("./public"));


var storage = multer.diskStorage({

destination: "./public/images",
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})



var upload = multer({ storage: storage }).array('file');


app.post('/upload',function(req, res) {
 
upload(req, res, function (err) {
       if (err instanceof multer.MulterError) {
           return res.status(500).json(err)
       } else if (err) {
           return res.status(500).json(err)
       }
  return res.status(200).send(req.file)

})

});

const PORT = process.env.PORT || 5000;
app.listen(PORT, ()=> {
console.log("server started at port "+PORT);
});

React frontend code:

import React, { useState } from 'react';
import axios from "axios";

const ImageForm = () => {

const [file, setFile] = useState(null);


const handleFileChange = (event) => {
    setFile(event.target.files);
    console.log(file)
}


const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData();
    for(var x = 0; x<file.length; x++) {
        data.append('file', file[x])
    }
    axios.post("http://localhost:5000/upload", data)
    .then(res => { 
        console.log(res.statusText)
      })
}

return ( 
    <div>
       <form >
        <div className="form-group" >

            <label htmlFor="file">Upload File:</label>
            <input 
            className="form-control-file mb-3" 
            type="file" id="file" 
            accept=".jpg"
            multiple
            onChange={handleFileChange}
            />

            <button 
            className="btn btn-primary mt-3" 
            onClick={handleSubmit}
            >Upload</button>
        </div>
       </form>

       {/* Display Image Here */}
    </div>
 );
}

export default ImageForm;

res: response

error: err


Solution

  • Firstly, create a state:

    const [imgFile, setImgFile] = useState('');
    

    Then, replace the following part of your code:

    axios.post("http://localhost:5000/upload", data)
    .then(res => { 
        setImgFile('http://localhost:5000/public/images/'+res.data.filename)
      })
    

    Add this after the form tag

    <img src={imgFile} alt="img"/>
    

    Just in case the image does not load, add this in the express code:

    app.use('/public/images', express.static(__dirname + '/public/images/'));