NodeJS Multer无法正常工作。

16

我尝试使用NodeJS + ExpressJS + Multer进行文件上传,但是没有成功。

我的ExpressJS版本是4.12.3

这是我的源代码

server.js:

var express = require('express'),
    multer  = require('multer');

var app = express();
app.use(express.static(__dirname + '/public'));
app.use(multer({ dest: './uploads/'}));

app.post('/', function(req, res){
    console.log(req.body); // form fields
    console.log(req.files); // form files
    res.status(204).end()
});
app.get('/', function(req, res)  {
    res.sendFile('public/index.html');
});

app.listen(5000, function() {
    console.log("start 5000");
});

公共/index.html:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input id="file" type="file"/>
        <button type="submit">test</button>
    </form>
</body>
</html>

当我点击提交按钮时,我的NodeJS控制台日志如下:

"C:\Program Files\nodejs\node.exe" server.js
start 5000
{}

在NodeJS控制台上,req.files处存在一个空对象。这是我的源代码有问题吗?


该表单是否实际触发了端点 app.post('/', function(req, res) - rjmacarthy
你的文件输入没有name属性,此外你仍需要使用body-parser来获取req.body - Ben Fortune
@RichardMacarhy 是的,这是正确的。 - DingGGu
@BenFortune 抱歉,这是我的源代码的一部分。我将它复制到我的项目中以提问。也许是我的错误。无论如何,multer 不起作用。 - DingGGu
@DingGGu 我的意思是输入需要一个name属性。 - Ben Fortune
显示剩余2条评论
2个回答

16

我没有看到你在单击提交按钮时调用任何API来上传文件。让我给你提供更全面的实现。

app.js中的multer配置

app.use(multer({ 
    dest: './uploads/',
    rename: function (fieldname, filename) {
        return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
    },
    onFileUploadStart: function (file) {
        console.log(file.fieldname + ' is starting ...')
    },
    onFileUploadData: function (file, data) {
        console.log(data.length + ' of ' + file.fieldname + ' arrived')
    },
    onFileUploadComplete: function (file) {
        console.log(file.fieldname + ' uploaded to  ' + file.path)
    }
}));

查看

<form id="uploadProfilePicForm" enctype="multipart/form-data" action="/user/profile_pic_upload" method="post">
          <input type="file" multiple="multiple" id="userPhotoInput" name="userPhoto"  accept="image/*" />
          <input type="submit" name="submit" value="Upload">
</form> 

终点'/user/profile_pic_upload'的POST调用在控制器中调用uploadProfilePic

var control = require('../controllers/controller');
app.post('/user/profile_pic_upload',control.uploadProfilePic);

在用户控制器中上传个人资料图片的逻辑

uploadProfilePic = function(req,res){
    // get the temporary location of the file
    var tmp_path = req.files.userPhoto.path;
    // set where the file should actually exists 
    var target_path = '/Users/narendra/Documents/Workspaces/NodeExpressWorkspace/MongoExpressUploads/profile_pic/' + req.files.userPhoto.name;
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;
        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) {
                throw err;
            }else{
                    var profile_pic = req.files.userPhoto.name;
                    //use profile_pic to do other stuffs like update DB or write rendering logic here.
             };
            });
        });
};

1
根据 readme 上的文档 https://github.com/expressjs/multer,我不认为这些选项(除了 dest)是当前的 multer 选项。 - lfender6445
@lfender6445 是的,你说得对。我花了大约一个小时来弄清楚为什么 onFile* 函数没有被调用。 - nnrales
1
它报错了:app.use()需要一个中间件函数 - Jaydeep Karena
抱歉,那是我的错误。找到解决方案了。我使用了 res 而不是像 function(req, res,......) 中的 file - Jaydeep Karena

2

试试这个

var multer = require('multer')

var storage = multer.diskStorage({
    destination: function (request, file, callback) {
        callback(null, './uploads/');
    },
    filename: function (request, file, callback) {
        console.log(file);
        callback(null, file.originalname)
    }
});

var upload = multer({ storage: storage });

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

    console.log(req.body) // form fields
    console.log(req.file) // form files
    res.status(204).end()
});

参考: http://wiki.workassis.com/nodejs-express-get-post-multipart-request-handling-example/


1
这个对我来说最好用了,谢谢你,我的英雄。 - gray
这种方法在本地主机上对我有效。但在生产环境中,它不起作用。 - Pranu Pranav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接