【问题标题】:How to send data along with file in http POST (angularjs + expressjs)?如何在http POST(angularjs + expressjs)中与文件一起发送数据?
【发布时间】:2017-04-08 00:06:17
【问题描述】:

情况

我实现了文件上传。前端代码取自流行的tutorial。我在服务中发送 POST:

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        
        $http.post(uploadUrl, fd, {
             transformRequest: angular.identity,
             headers: {'Content-Type': undefined}
        })
        
        .success(function(){
        })
       
        .error(function(){
         });
        }
    }]);

后端的典型 multer 用法:

exports.postFile = function (req, res) {

    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, '../documents/')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
    });

    var upload = multer({ //multer settings
        storage: storage
    }).single('file');

    upload(req, res, function (err) {
        if (err) {
            res.json({error_code: 1, err_desc: err});
            return;
        }
        res.json({error_code: 0, err_desc: null});
    })

};

这行得通。

问题

如何在同一个 POST 中发送一些数据,比如说字符串"additional info"

我尝试了什么

我尝试在服务中添加数据,即:

...
var fd = new FormData();
fd.append('file', file);
fd.append('model', 'additional info');

$http.post(uploadUrl, fd, {...})

好像是发送的,但是后台不知道怎么接收。试图在req 中找到它(没有成功)。

【问题讨论】:

    标签: angularjs express multer


    【解决方案1】:

    你可以这样做:

              $http({
                    url: url, 
                    method: 'POST',
                    data: json_data,
                    headers: {'Content-Type': 'application/json'}
              }).then(function(response) {
                    var res = response.data;
                    console.log(res);
              }, function errorCallback(response) {
                  // called asynchronously if an error occurs
                 // or server returns response with an error status.
              });
    

    或者只是将 data 属性添加到您的函数中。

        var userObject = {
        email: $scope.user.email,
        password: $scope.user.password,
        fullName: $scope.user.fullName
        };
    
        $http.post(uploadUrl, fd, {
             transformRequest: angular.identity,
             data: userObject,
             headers: {'Content-Type': 'application/json'}
        })
    

    您可以在后端尝试类似的操作。

    req.on('data', function (chunk) {
        console.log(chunk);
    });
    

    【讨论】:

    • 这个 POST 中的文件在哪里?
    • 你说的是一些字符串数据。
    • 我的意思是字符串和文件,正如标题所说。
    • 关于上次编辑:我为什么要在服务器响应中查找它?
    • 对不起。是req.on。我会改变的。看第二个答案。希望对您有所帮助!
    【解决方案2】:

    您可以从 req.files 中获取文件并使用 fs.writeFile 保存。

    fs.readFile(req.files.formInput.path, function (err, data) {
      fs.writeFile(newPath, data, function (err) {
        if (err) {
        throw err;
        }
        console.log("File Uploaded");
      });
    });
    

    【讨论】:

    • 发送端接收文件没有任何问题。有用。我想在同一个 POST 请求中发送(和接收)附加数据(连同文件)。
    • 您可以使用 $http.post 中的 data 属性发送一个包含您想要的所有其他数据的对象,发送所有输入。
    • 我已经修改了第一个答案,展示了如何从所有输入中传递数据,假设您的输入文件中有一个 ng-model="user.email" 等。
    【解决方案3】:

    要在一个 POST 请求中发送数据(即 json)和文件,请将两者都添加到表单数据中:

    myApp.service('fileUpload', ['$http', function ($http) {
        this.uploadFileToUrl = function(file, uploadUrl){
            var fd = new FormData();
            fd.append('file', file);
    
            var info = {
                "text":"additional info"
            };
            fd.append('data', angular.toJson(info));
    
            $http.post(uploadUrl, fd, {
                 transformRequest: angular.identity,
                 headers: {'Content-Type': undefined}
            })
    
            .success(function(){
            })
    
            .error(function(){
            });
        }
    }]);
    

    在服务器端它在req.body.data,所以它可以被接收,例如:

    upload(req, res, function (err) {
        if (err) {
            res.json({error_code: 1, err_desc: err});
            return;
        }
    
        console.log(req.body.data);
    
        res.json({error_code: 0, err_desc: null});
    })
    

    【讨论】:

    • 感谢您提供这个有用的答案。解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多