簡體   English   中英

NodeJS Multer無法正常工作

[英]NodeJS Multer is not working

我嘗試使用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上有空對象我的源代碼有問題嗎?

我沒有看到你在點擊提交按鈕時調用任何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調用控制器中的uploadProfilePic

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

在用戶控制器中上傳配置文件pic邏輯

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

使用這個例子,它使用firebase雲功能和firebase存儲上傳文件,但你可以使用它做任何事情,它使用快速多部分文件解析器和像魅力上面的鏈接工作完美,我測試了這段代碼並推送它為你們回購。只需添加你的配置就可以了。

試試這個

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM