Home > Software engineering >  Not able to POST image files to server
Not able to POST image files to server

Time:10-20

I'm trying to send an image to server using POST request but on server side I'm receiving and empty object.

  // Client Side

  function uploadFile(thumbnailRef) {
    const thumbnail = thumbnailRef.current.files[0];
    const formData = new FormData();
    formData.append('file', thumbnail)

   fetch('http://localhost:8080/upload', {
        method: 'POST',
        body: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
        },

    }).then(res => { console.log(res) })
        .catch(err => console.log(err))

  }
  // server side

  app.post('/upload', (req, res) => {
    console.log(req.body) // getting empty - {}
    res.end()
})

CodePudding user response:

I think it should work if you remove headers. Like this:

function uploadFile(thumbnailRef) {
    const thumbnail = thumbnailRef.current.files[0];
    const formData = new FormData();
    formData.append('file', thumbnail)

   fetch('http://localhost:8080/upload', {
        method: 'POST',
        body: formData,

    }).then(res => { console.log(res) })
        .catch(err => console.log(err))

  }

CodePudding user response:

Did you use any file upload libraries like "multer", "express-fileupload"? It will be much more easier for you to do that stuff.

Check this website

  • Related