Express parsing multipart/form-data post in req.body

落花浮王杯 提交于 2019-12-05 07:14:36

问题


I'm trying to upload a file using jQuery Ajax + FormData object found on Chrome and Firefox browsers. The code I'm using to do it is the following:

var formData = new FormData();
    formData.append('image', $scope.image.data);

     $.ajax({
       url: '/wines/'+id+'/image',
       type: 'POST',
       data: formData,
        processData:false,
        contentType:false
     }).done(function(){
       $location.path('/');
     });

By looking at the developer tools I can see that the request is formed correctly, however express is recognising the contents inside req.body instead of req.files. Here is the request payload image:

Express config:

app.configure(function(){
app.set('views', __dirname + '/app');
app.engine('.html', require('ejs').renderFile)
app.use(express.static(__dirname + '/app'));
app.use(express.bodyParser());
app.use(express.methodOverride());

app.use(app.router);
});

What's what I am doing wrong?? Thanks a lot.


回答1:


Because its not a file, its just a string. To AJAX a file with FormData you have to pass a File object to FormData.append what you are passing is a data uri which is just a string.

A file in a multipart/form-data body looks something like this

------WebKitFormBoundaryNBylbsEYlWSsq2lB
Content-Disposition: form-data; name="image"; filename="999.jpg"
Content-Type: image/jpeg

The file content here
------WebKitFormBoundaryNBylbsEYlWSsq2lB--


来源:https://stackoverflow.com/questions/14887681/express-parsing-multipart-form-data-post-in-req-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!