使用http post方法上传angular js文件

时间:2014-09-01 13:12:35

标签: javascript node.js angularjs multipartform-data

我想使用angular $ http方法将一个文件上传到节点后端

我想上传包含其他表单字段的表单。

这是我的代码

        var data = new FormData();
        data.append('title', 'sometitle');
        data.append('uploadedFile', $scope.uploadedFile);
        FileService.upload(url, data, function(data, status) {
          if(status===HTTP_OK) {
            $scope.uploadSuccess = true;
            $scope.showUploadProgressBar = false;
          } else {
            // error occured
            console.log(data);
          }
        });

的FileService

FileService.upload = function(url, data, callback) {
    $http({
        method : 'POST',
        url : url,
        data : data,
  headers: {'Content-Type': undefined },
  transformRequest: angular.identity
    }).success(function(data, status) {
        callback(data, callback);
    }).error(function(data, status) {
        callback(data, status);
    });
};

我正在使用节点多方模块进行文件上传。我正确地收到了文件。但是标题的字段值是未定义的。

我不知道为什么标题值未定义

Node.js后端文件上传处理程序

var form;
if(options.uploads.tempDir) {
  form = new multiparty.Form({uploadDir : options.root + '/' + options.uploads.tempDir});
} else {
  form = new multiparty.Form();
}
form.on('file', function(name, receivedFile) {
  var tmpPath = receivedFile.path,
    fileName = receivedFile.originalFilename,
    targetDirectory = uploadDirectory + '/' + req.params.id,
    targetPath = targetDirectory + '/' + fileName,
    file = {
      filePath : targetPath,
      tempPath : tmpPath,
      fileName : fileName,
      size : receivedFile.size
    };

  fileUploadStatus.file = file;
  // move file
  fse.move(tmpPath, targetPath, function(err) {
    if(err) {
      console.log('Error moving file [ ' + targetPath + ' ] ' + JSON.stringify(err));
    }
  });
});

form.on('error', function(err) {
  fileUploadStatus.err = err;
  req.fileUploadStatus = fileUploadStatus;
  next();
});

form.on('close', function() {
  req.fileUploadStatus = fileUploadStatus;
  next();
});
form.on('field', function(name, value) {
  console.log('field called');
  console.log(name);
  console.log(value);
  req.body = req.body || {};
  req.body[name] = value;
});

// ignoring parts. Implement any other logic here
form.on('part', function(part) {
  var out = new stream.Writable();
  out._write = function (chunk, encoding, done) {
    done(); // Don't do anything with the data
  };
  part.pipe(out);
});

// parsing form
form.parse(req);

0 个答案:

没有答案