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

How to upload a file with AngularJS and save it with ExpressJS?

本文关键字:并用 ExpressJS 保存 文件 何用 AngularJS      更新时间:2023-09-26

我在AngularJS中使用了一个名为angular-file-upload的指令。我已经设置好了,图像上传工作正常,但是我似乎无法将文件解析到服务器端(express 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);
};

对于express,控制台总是打印出以下内容:

 {}
 undefined

有什么问题吗?

在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
    });
};

然而,这是一个安全风险(保存到磁盘),这就是为什么需要。文件已经不存在了),所以大多数处理文件的库(例如Cloudinary)都提供了WriteStream(或者看起来和感觉上都像的东西)。下面是它如何与cloudary一起工作的:

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);
    });
};
我复制了你的代码并测试了它,它工作得很好。如果你有任何问题,请告诉我。我一周前也遇到过同样的问题,所以我去调查了一下。

tgkokk使用Cloudinary的示例不再适用于Cloudinary v1.1.1。Cloudinary更新了upload_stream方法以返回一个Transform流对象。所以使用'pipe'代替手动添加事件到on('data')和on('end')。

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);
    });
};