【问题标题】:AngularJS File Upload to Backend Express ServerAngularJS 文件上传到后端 Express 服务器
【发布时间】:2014-11-19 14:45:04
【问题描述】:

我正在尝试使用 angularjs 进行文件上传,使用 angular-file-upload 库 (https://github.com/danialfarid/angular-file-upload)

这是我的代码

// ===============================My HTML File===========================
<input type="file" ng-file-select="onFileSelect($files)">


// ===============================My Controller==========================
var $scope.formObj = {
  name: "Test"
};

var fileToUpload;

$scope.onFileSelect = function (file) {
 fileToUpload = file[0];
};

// POSt request to /api/items
$scope.addItem = function() {
  console.log($scope.formObj);
  $scope.upload = $upload.upload({
   url: '/api/items',
   method: 'POST',
   data: { myObj: $scope.formObj },
   file: fileToUpload
  }).success(function(data, status, headers, config) {
   console.log("success");
  });
};


// ================================My Backend=============================

// This is the function that will receive POST request to /api/items
exports.create = function(req, res) {
  console.log(req.body); // req.body is just an empty object. ==> {}

  // apparently, I found all the data to be in req._readableState.buffer[0]
  // in the form of a buffer
  var buffer = req._readableState.buffer[0];

  // trying to console.log the buffer.toString, resulting in something similar to this
  // { name: "Test", image: Object }
  console.log(buffer.toString());

  return res.send(200);
};

所以我的后端收到了 formObj 及其所有属性和值,但是,实际的文件数据本身,无论是缓冲区形式,还是 base64 形式,或其他形式,都不会被接收到。

我想知道为什么。这是我第一次使用文件上传,所以我不明白这个概念。

请指出正确的方向

【问题讨论】:

    标签: html angularjs file-upload express angularjs-directive


    【解决方案1】:

    如果您使用的是最新版本的 Express,您会注意到

    app.use(express.multipart()); 不再与 express 捆绑在一起。

    请进行以下配置更改。在 express.js 中

    var multer = require('multer');
    
    app.use(multer({ dest: './uploads/'}));
    

    你会发现这样做之后你会分别在 req.body req.file 中找到 data 和 file 。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-05-16
      • 1970-01-01
      • 2021-06-24
      • 2017-07-04
      • 2018-05-17
      • 2012-03-19
      • 2021-12-06
      • 2014-06-10
      • 2021-08-14
      相关资源
      最近更新 更多