AngularJS文件上传到后端Express Server

时间:2014-09-24 23:37:19

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

我正在尝试使用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,或者其他什么,都不会被接收。

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

请指出正确的方向

1 个答案:

答案 0 :(得分:0)

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

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

以下配置更改也是如此。在express.js

var multer = require('multer');

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

您会发现在执行此操作后,您将分别在req.body req.file中找到数据和文件。

希望有所帮助