提问者:小点点

如何使用FormData和multer在节点js上传文件,我在req.file中得到未定义,在req.body中得到{}


下面是html代码

HTML

<input type="file" name="file" id="file" onchange="angular.element(this).scope().uploadFile(this.files)">

下面是javascript代码

JavaScript

$scope.uploadFile = function (files) {
        var fd = new FormData();
        //Take the first selected file
        console.log("files", files);
        fd.append("file", files[0]);
        $http({
            method: 'POST',
            url: 'http://localhost:5000/upload',
            headers: {
                'Content-Type': undefined
            },
            data: fd

        }).then(function (response) {
        }, function (error) {
        });

    };

以下是服务器端代码

服务器端

var http = require('http');
var express = require('express');
var cors = require('cors');
var multer = require('multer');
var bodyParser = require('body-parser');
var upload = multer({ dest: 'public' });
var app = express();

app.use(cors());
app.use(bodyParser.json())

app.use(express.static('public'))

app.get('/', function (req, res) {
  res.sendStatus(200)
})


app.post('/upload', upload.single('file'), function (req, res) {

  console.log("req.file", req.file); //req.file undefined
  console.log("req.body", req.body); //req.body {}

});

app.listen(5000, function () {
  console.log("server listening on port 5000 ");

})

为什么我得到了这个结果,如何使用angularjs在multer的帮助下在文件夹中的节点js上传文件


共1个答案

匿名用户

后端代码看起来不错,但是您需要在客户端设置正确的内容类型。

通过提供form-data作为其data参数,您实际上应该不必明确地定义content-type。 所以你可以简单地做:

$http('http://localhost:5000/upload', fd)

如果要显式指定内容类型,可以使用:

$http('http://localhost:5000/upload', fd, {
    headers: {
        'content-type': 'multipart/form-data'
    }
})