2

Im using multer for the first time and I have some trouble with it.

I would like to upload image file on my server from a react client with superagent lib.

But the req.file data is always undefined, here is my code :

Server side :

const upload = multer({ 
    dest: 'uploads/' })
app.post('/uploadprofile', upload.single('profil'), (req, res) => {
        console.log(req.file);
        console.log(req.files);
        console.log(req.body);
        res.status(200).end()
})

And my client side :

onUploadFile(e) {
        console.log(e.target.files[0])
        this.setState({
            img: e.target.files[0]
        }, () => {
            agent
            .post("http://localhost:3100/uploadprofile")
            .attach('profil', this.state.img, this.state.img.name)
            .set("Content-Type", "")
            .end((err, res) => {
                console.log(err)
                console.log(res)
                console.log("send")
         })
        })
    }


render() {
return (
    <input id="file" type="file" accept="image/*" name="profil" className="inputButton" onChange={this.onUploadFile}/>
)
}

In my superagent request, I have to overwrite the content-type, otherwise json data are send.

But the req.file is still undefined on my backend.

Thanks for the help !

Paul
  • 101
  • 1
  • 1
  • 12

1 Answers1

0

The issue is with your superagent call, check this page: https://visionmedia.github.io/superagent/#multipart-requests

According to it:

When you use .field() or .attach() you can't use .send() and you must not set Content-Type (the correct type will be set for you).

So you need to remove .set("Content-Type", ""), and do something like this:

      await superagent
        .post(url)
        .withCredentials()
        .accept('application/json')
        .field('lets_try', 'ok!')                 // this would come from a form field
        .attach('staff', event.target.files[0]);  // this is your file

On the server side, once you get your (single) file, you still have to convert its buffer to string, if you expect some text:

  console.log(`Uploaded req.body=${JSON.stringify(req.body)}`);
  console.log(`         req.file=${JSON.stringify(req.file, null, 2)}`);
  console.log(`req.file=${req.file.buffer.toString()}`);

You will get:

Uploaded req.body={"lets_try": "ok!"}
         req.file={
   "fieldname": "staff",
   "originalname": "test.json",
   "encoding": "7bit",
   "mimetype": "application/json",
   "buffer": {
     "0": 10,
     "1": 98,
     "2": 111,
     "3": 98,
     "4": 10,
   },
   "size": 5,
 }
req.file=
 bob

If your file content is bob :-)

Will59
  • 1,430
  • 1
  • 16
  • 37