最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS Multer is not working - Stack Overflow

programmeradmin0浏览0评论

I tried to file upload with NodeJS + ExpressJS + Multer but does not work well.

My ExpressJS Version is 4.12.3

this is my source

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");
});

public/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>

My NodeJS Console Log when I click Submit Button:

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

on NodeJS Console, there is empty object at req.files Is some problem on my source?

I tried to file upload with NodeJS + ExpressJS + Multer but does not work well.

My ExpressJS Version is 4.12.3

this is my source

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");
});

public/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>

My NodeJS Console Log when I click Submit Button:

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

on NodeJS Console, there is empty object at req.files Is some problem on my source?

Share Improve this question edited Apr 7, 2015 at 12:56 potashin 44.6k11 gold badges89 silver badges112 bronze badges asked Apr 7, 2015 at 11:46 DingGGuDingGGu 1851 gold badge1 silver badge11 bronze badges 6
  • Does the form actually hit the endpoint? app.post('/', function(req, res)? – rxjmx Commented Apr 7, 2015 at 12:11
  • Your file input doesn't have a name attribute, plus you still need body-parser for req.body. – Ben Fortune Commented Apr 7, 2015 at 12:15
  • @RichardMacarhy yeah. this is correct. – DingGGu Commented Apr 7, 2015 at 15:28
  • @BenFortune sorry, this is part of my source. I copied to my project for question. maybe my mistakes. whatever multer doesn't work well. – DingGGu Commented Apr 7, 2015 at 15:30
  • @DingGGu What I'm saying is inputs require a name attribute. – Ben Fortune Commented Apr 7, 2015 at 15:31
 |  Show 1 more comment

2 Answers 2

Reset to default 17

I don't see you calling any API to upload file on click of submit button. Let me give you more comprehensive implementation.

multer config in app.js

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)
    }
}));

View

<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> 

End point '/user/profile_pic_upload' POST calls uploadProfilePic in controller

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

Upload profile pic logic in users controller

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.
             };
            });
        });
};

Try this

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()
});

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

发布评论

评论列表(0)

  1. 暂无评论