问题
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