【问题标题】:Handling FormData in nodejs and angularJs在 nodejs 和 angularJs 中处理 FormData
【发布时间】:2018-02-07 10:17:47
【问题描述】:

我有一个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>

【问题讨论】:

  • 能否请您也发布您的html 代码?

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


【解决方案1】:

像这样为您的fd 变量添加范围,

更改您当前的 fd 声明,

var fd = new FormData();

到,

$scope.fd = new FormData();

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

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

希望这会有所帮助!

【讨论】:

  • 你能用你的html代码更新你的帖子吗?
【解决方案2】:

如图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 ... })

【讨论】:

    猜你喜欢
    • 2014-12-05
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多