question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Image Upload with FormData() not work(react + express)

See original GitHub issue

WritingForm.js

import React, { Component } from "react";
import axios from "axios";

class WritingForm extends Component {
  state = {
    selectedFile: null
  };

  handleSubmit = async () => {
    const { selectedFile } = this.state;

    const fd = new FormData();
    fd.append("img", selectedFile); // 파일 하나 state를 거쳐서 서버로 전송

    const contentType = {
      headers: { "content-type": "multipart/form-data" }
    };

    axios
      .post("/post/test", fd, contentType)
      .then(res => console.log(res))
      .catch(e => console.log(e));
  };

  handleFileChange = e => {
    this.setState({
      selectedFile: e.target.files[0]
    });
    console.log(e.target.files[0]);
  };

  render() {
    return (
      <center>
        <div>
          <input
            id="img"
            name="img"
            type="file"
            className="input"
            onChange={this.handleFileChange}
          />
          <input
            type="button"
            value="Submit"
            className="submit"
            onClick={() => {
              this.handleSubmit();
            }}
          />
        </div>
      </center>
    );
  }
}

export default WritingForm;


post.js

const router = require('express').Router()
const multer = require('multer')
const path = require('path')

const upload = multer({
  storage: multer.diskStorage({
    destination(req, file, cb) {
      cb(null, 'uploads/');
    },
    filename(req, file, cb) {      
      const ext = path.extname(file.originalname);
      cb(null, path.basename(file.originalname, ext) + new Date().valueOf() + ext);
    },
  }),
})

// didn't upload image in upload directory
router.post('/test',upload.single('img'), async (req,res, next)=>{
  try{
    console.log(req.file)         // undefined
    console.log(req.files)        // { img:   { name: 'name.jpg',    
                                                    //  data: <Buffer ff d8 ff e1 28 bc 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 0c 00 0e 01 02 00 20 00 00 00 9e 00 00 00 0f 01 02 00 0500 00 00 be 00 00 00 10 01 02 00 ... >,
                                                    //  encoding: '7bit',
                                                    //  truncated: false,
                                                    //  mimetype: 'image/jpeg',
                                                    //  md5: [Function: md5],
                                                    //  mv: [Function: mv] } }
    res.send({"ret":"success"})


  }catch(e){
    console.log(e)
    res.send({'ret':'err'})
    next(e) 
  }
})


Hello, I’m a student in South Korea, and I have difficult in using multer with react.

I studied when upload.single(‘img’) did work, image files should be uploaded to ‘uploads’ directory and req.file should contain information of file.

But only I have is req.files, despite i used upload.single(), not upload.array()

‘req.files’ is the only variable that contain file information from front-end. How can I actually upload file to my ‘upload’ directory?

Thank you for your help, and sorry for my bad English.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
YanghaKoocommented, Oct 2, 2018

oh i fixed it.

There was another middleware that consuming body in my app.js, outside of router!! Thank you for your kind comment.

@brunosiqueira maybe your problem is same as mine!

1reaction
brunosiqueiracommented, Oct 2, 2018

Thanks for the tip, @YanghaKoo ! It was my case too! The express-fileupload middleware started to interfere with multer. Now it is working fine!

Read more comments on GitHub >

github_iconTop Results From Across the Web

FormData doesn't work on upload files in React project with ...
I have a full MERN stack project with Redux and AXIOS. I used FormData to upload the images to my node ...
Read more >
Uploading Images – Express and React - Sam Meech-Ward
In this article I'm going to show you how to upload an image from a react app to an express server using a...
Read more >
How to Multipart File Upload Using FormData with React Hook ...
In this guide, I'm going to show you how to multipart files upload with using React Hook Form.
Read more >
How to Upload File/Image to Server with Form ... - About React
Pick a file using any file picker. · Create FormData by creating an object and appending the values you want to send to...
Read more >
How to Upload File/Image to Server with Form Data ... - YouTube
In this video, I'll show you how to Upload File/ Image to Server with Form Data in React Native. This example will cover...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found