Error uploading files using Multer in NodeJs

假如想象 提交于 2019-11-29 18:03:31

Working on sometime I got a solution using multer module.Using this module you can upload both files and images.And it successfully uploaded to the destination folder.

Here is my server code app.js

var express =r equire('express');
var multer = require('multer');
var path = require('path')
var app = express();
var ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './public/uploads')//here you can place your destination path
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

app.get('/api/file',function(req,res){
res.render('index');
});
app.post('/api/file', function(req, res) {
    var upload = multer({
        storage: storage}).single('userFile');
    upload(req, res, function(err) {
        console.log("File uploaded");
        res.end('File is uploaded')
    })
})

app.listen(3000,function(){
console.log("working on port 3000");
});

Create a views folder and place this index.ejs file in it

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data" method="post">
        <input type="file" name="userFile" />
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>

After this run the server as node app.js.Open the browser and type http://localhost:3000/api/file after runnig this url choose a file which you want to upload to destination folder.And have a successfull response in both terminal and browser.Hope this helps for you.

I got your code working. See:

https://gist.github.com/lmiller1990/3f1756efc07e09eb4f44e20fdfce30a4

I think the problem was with the way you declared destination. I'm not sure why, though. I got it working by just passing the path as a string.

Best of luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!