在nodejs和angularJs中处理FormData

时间:2018-02-07 10:17:48

标签: javascript angularjs node.js google-cloud-storage

我在html中有一个文件上传表单,提交后我将用户输入文件作为formData,我将从angularjs触发nodejs api。

在nodejs中 - 我想接收formData并上传到一些外部存储器。该外部存储还需要输入文件作为formData。

但是我无法在nodejs中接收formData作为formData。

请有人建议解决方案。

$scope.add = function(file) {

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

    $http.post('/uploadFile', fd, {headers: {'Content-Type': undefined}}).then(function(response) {

       console.log(response);
    }, function errorCallback(response) {
        console.log(response);

    });
}

的NodeJS

app.post('/uploadFile', function (req,res) {
    console.log(req.body); //Undefined
})

HTML

<form name="addForm" ng-submit="add(videoFile)">
 <input class="file-upload__input" type="file" file-model="videoFile" required>
</form>

2 个答案:

答案 0 :(得分:0)

将范围添加到您的fd变量中,

更改fd的当前声明,

var fd = new FormData();

要,

$scope.fd = new FormData();

在发布时,将其发布为像这样的范围变量,

$http.post('/uploadFile', $scope.fd, {headers: {'Content-Type': undefined}}).then(function(response) {

希望这有帮助!

答案 1 :(得分:0)

如图所示in this repository

要记录req.files

服务器端:

const formData = require('express-form-data');
const multipartyOptions = {
        autoFiles: true
      };

// parse a data with connect-multiparty. 
app.use(formData.parse(multipartyOptions));
// clear all empty files (size == 0)
app.use(formData.format());
// change file objects to node stream.Readable 
app.use(formData.stream());
// union body and files
app.use(formData.union())

客户方:

<input id="i1" type="file">

formData = new FormData();
formData.append('image', i1.files[0]);
$http.post('http://localhost:3000/upload', formData, { ... omissis ... })