在req.body中快速解析multipart / form-data post [英] Express parsing multipart/form-data post in req.body

查看:1890
本文介绍了在req.body中快速解析multipart / form-data post的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Chrome浏览器和Firefox浏览器上的jQuery Ajax + FormData对象上传文件。我使用的代码如下:

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('/');
     });

通过查看开发人员工具,我可以看到请求正确形成,内容里面的req.body而不是req.files。以下是请求有效载荷图像:

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:

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.

推荐答案

因为它不是一个文件,它只是一个字符串。要使用 FormData 的AJAX文件,您必须将File对象传递给 FormData.append 您传递的是一个数据uri只是一个字符串。

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.

multipart / form-data 正文中的文件看起来像这样

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

这篇关于在req.body中快速解析multipart / form-data post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆