Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

node.js - Error uploading files using Multer in NodeJs

I am trying to write an Express-based API for uploading files. The filename and directory path should be set dynamically.

My code:

var crypto = require('crypto')
var express = require('express');
var fs = require('fs');
var mime = require('mime');
var mkdirp = require('mkdirp');
var multer = require('multer');

var app = express();
var path = './uploads'; 

var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, path);
        console.log('Im in storage destination'+path);
    },
    filename: function (req, file, callback) {
        console.log('Im in storage filename'+path);
        //callback(null, file.fieldname + '-' + Date.now());
        crypto.pseudoRandomBytes(16, function (err, raw) {
            callback(null, Date.now() + '.' + mime.extension(file.mimetype));
        });
    }
});

var upload = multer({ storage : storage}).single('userPhoto');

app.post('/photo',function(req,res){
    path += '/pics/shanmu/';
    console.log('Im in post , outside upload'+path);

    upload(req,res,function(err) {
        console.log('Im in post , inside upload'+path);
        if(err) {
            return res.end('Error uploading file.');
        }
        res.end('File is uploaded'+path);
        console.log('File is uploaded'+path);
    });
});

app.listen(3000,function(){
    console.log('Working on port 3000');
});

My folder structure:

When I run the code, the file should be uploaded in the uploads/ folder. (This folder has two nested folders inside it - uploads/pics/shanmu).

When I triggered it from postman, it only works once. When I try the second time, I cannot upload files.

Please advise.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...