无法将文件从AngularJS上传到ExpressJs

时间:2014-05-17 10:08:31

标签: javascript angularjs express mean-stack

我现在使用angular-file-upload包上传文件。按下item.upload()之后,它声称已成功上传文件,但我看到req.body为空。请帮助!

这是处理它的角度代码:

var uploader = $scope.uploader = $fileUploader.create({
        scope: $scope,                          // to automatically update the html. Default: $rootScope
    url: '/api/teams/upload',
    formData: [
        { key: 'value' }
    ],
    filters: [
        function (item) {                    // first user filter
            $scope.previewImage(item);
            return true;
        }
    ]
});

以下是触发上传的方法:

uploader.bind('afteraddingfile', function (event, item) {
    // console.info(item.file);
    console.info('After adding a file', item);

    // console.log('item.upload();');
    item.upload();
});

最后这里是快递js代码:

exports.upload = function(req, res) {
// console.log('req.headers');
// console.log(req.headers);

console.log('req.body');
console.log(req.body);

它有什么不妥之处?

1 个答案:

答案 0 :(得分:0)

首先确保您的POST编码为enctype="multipart/form-data" ....

在Express 4中,您需要在服务器中设置body parser

var bodyParser     = require('dy-parser');
//...

var app            = express();
//...
app.use(bodyParser());  // pull information from html in POST

var busboy = require('connect-busboy');    
app.use(busboy());

在早期版本的Express中,您只需要从框架本身添加正文解析器,文件将存储在配置的位置:

     app.use(express.bodyParser({limit: '10mb', uploadDir: __dirname + '/public/uploads' }));               // pull information from html in POST

由于版本4现在删除了对connect的支持,因此您需要将多部分/表单数据的自定义支持添加到解析器多部分/部分POST,因此您必须执行以下操作:

var fs = require('fs');
var busboy = require('connect-busboy');

//...
app.use(busboy()); 
//...
app.post('/api/teams/upload', function(req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename) {
        console.log("Uploading: " + filename); 
        fstream = fs.createWriteStream(__dirname + '/files/' + filename);
        file.pipe(fstream);
        fstream.on('close', function () {
            res.redirect('back');
        });
    });
});

在客户端,您需要致电$upload.upload开始上传