如何使用AngularJS上传文件并使用ExpressJS保存?

时间:2014-07-21 18:34:59

标签: javascript angularjs express

我正在使用一个名为angular-file-upload的AngularJS指令。我已经设置好了,图片上传工作正常,但我似乎无法将文件解析到服务器端(表达js)。

玉:

input.form-input(ng-model="userAvatarFile" ng-file-select="onFileSelect($files)" name="userAvatarFile" type="file")

这是AngularJS的代码:

$scope.onFileSelect = function($files) {

    console.log($files);

    for (var i = 0; i < $files.length; i++) {
        var file = $files[i];
        $scope.upload = $upload.upload({
            url: '/api/user/upload', 
            method: 'POST',
            data: {myObj: $scope.userAvatarFile},
            file: file, 
        }).progress(function(evt) {
            console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
        }).success(function(data, status, headers, config) {
            console.log(data);
        });
    }
};

并表达:

exports.upload = function(req, res) {
  console.log(req.body);
  console.log(req.files);
};

控制台总是打印出以下快递:

 {}
 undefined

任何想法可能出错?

2 个答案:

答案 0 :(得分:0)

Connect 3.0中删除了多部分中间件。 Connect建议connect-multipartyconnect-busboy。恕我直言connect-busboy更好,所以这里是如何做到的:

(当然,运行npm install --save connect-busboy

// Main file, stays the same for all the other examples
var express = require('express'),
    busboy  = require('connect-busboy');

app.use(busboy({ immediate: true }));

// Route file
exports.upload = function (req, res) {
    req.busboy.on('file', function (fieldname, file, filename) {
        // fieldname will be 'file', file will be... um... the file (in binary encoding), filename will be the file's name
    });
    req.busboy.on('field', function (key, value) {
        // key will be 'myObj', value will be $scope.userAvatarFile
    });
};

如果要将图像保存到文件,可以执行以下操作:

exports.upload = function (req, res) {
    req.busboy.on('file', function (fieldname, file, filename) {
        // saveTo is the temporary path
        var saveTo = path.join(os.tmpDir(), path.basename(fieldname));
        file.pipe(fs.createWriteStream(saveTo));

        // Do stuff with saveTo
    });
};

然而,这是一个安全风险(保存到磁盘,这就是为什么req.files不再存在),所以大多数(?)库使用文件(例如Cloudinary)提供WriteStream(或看起来像什么感觉就像一个)。以下是Cloudinary的工作原理:

exports.upload = function (req, res) {
    req.busboy.on('file', function (fieldname, file, filename) {
        var stream = cloudinary.uploader.upload_stream(function(result) { console.log(result); });

        // You should have been able to do file.pipe(stream), but Cloudinary's stream isn't a real WriteStream, but just an object with two functions. Well, the following works too:

        file.on('data', stream.write);
        file.on('end', stream.end);
    });
};

FWIW,我复制了你的代码并测试了它,它运行得很好。如果你有任何问题,请告诉我。一周前我遇到了同样的问题,所以我要调查一下。

答案 1 :(得分:0)

使用Cloudinary的

tgkokk's示例不再适用于Cloudinary v1.1.1。 Cloudinary更新了upload_stream方法以返回Transform流对象。所以使用&#39; pipe&#39;而不是手动添加事件(&#39;数据&#39;)和(&#39;结束&#39;)。

https://github.com/cloudinary/cloudinary_npm#version-11-upload_stream-change-notes

exports.upload = function (req, res) {
    req.busboy.on('file', function (fieldname, file, filename) {
        var stream = cloudinary.uploader.upload_stream(function(result) {    console.log(result); 
        });

        // pipe can be used now
        file.pipe(stream);
    });
};