Home > Net >  Nodejs : Why we need to pass an object FormData so that multer can work well ( upload file I using a
Nodejs : Why we need to pass an object FormData so that multer can work well ( upload file I using a

Time:08-22

i'm learning nodejs and using multer , ajax jquery for uploaded file , but I feel a little confused. Assume i have this code in html file

  <form action="/" method='post' enctype="multipart/form-data" id='form-data'>
    <input type="file" name='file' id='file' class='file'>
  </form>

and the script:

<script>
    $(document).on('change', '#file', function () {
        var property = document.getElementById('file').files[0];
        var form_data = new FormData();
        form_data.append('file',  property);
        $.post({
            url: '/',
            type: 'post',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                console.log(data);
            }
        })
    })

</script>

In the server.js ( server side ) i have this code:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now()   path.extname(file.originalname))
  }
 })

var upload = multer({ storage: storage })


app.post('/', upload.single('file'), (req,res) =>{
  console.log(req.body);
  console.log(req.file);
})

This code run smoothly. But this questions that bother me:

In the script , line 9 , if i using "data : property" instead of "data: form_data", it doesn't work anymore , req.file is empty. Why can't we directly pass variable "property" into data but must use a object FormData to do it ?

CodePudding user response:

Multer is designed to parse data encoded using the multipart/form-data format (which consists of any number of bits of data (such as files and pieces of text) separated with boundary markers).

The FormData API lets you collect different pieces of data, including files, and generate multipart/form-data with them.

If you pass jQuery the value of property directly then you will be sending the file, which might be text/plain or image/png or just about anything, without any further encoding. It is highly unlikely to be multipart/form-data since people don't generally store data in that format.

You can write server side code that expects a raw file, but if you did that then you wouldn't be using Multer.

  • Related