How to send data along with file in http POST (angularjs + expressjs)?

后端 未结 3 1004
天命终不由人
天命终不由人 2021-01-14 02:41

Situation

I implemented file uploading. Front-end code is taken from popular tutorial. I send POST in service:

myApp.service(\'fileUpload\', [\'$http         


        
相关标签:
3条回答
  • 2021-01-14 03:22

    You can do something like this:

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

    Or just add the data property to your function.

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

    You can try something like this on the backend.

    req.on('data', function (chunk) {
        console.log(chunk);
    });
    
    0 讨论(0)
  • 2021-01-14 03:23

    To send data (i.e. json) and file in one POST request add both to form data:

    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(){
            });
        }
    }]);
    

    On server side it's in req.body.data, so it can be received i.e. like this:

    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});
    })
    
    0 讨论(0)
  • 2021-01-14 03:33

    You can get the file from req.files and save it with 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");
      });
    });
    
    0 讨论(0)
提交回复
热议问题