NodeJS Multer не работает

Я попытался загрузить файл с помощью NodeJS + ExpressJS + Multer, но не работает хорошо.

моя версия ExpressJS-4.12.3

Это мой источник

сервер.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>

мой журнал консоли NodeJS, когда я нажимаю кнопку отправки:

"C:Program Filesnodejsnode.exe" server.js
start 5000
{}

на консоли NodeJS есть пустой объект в req.файлы Какие-то проблемы с моим источником?

3 ответов


Я не вижу, чтобы вы вызывали какой-либо API для загрузки файла при нажатии кнопки отправки. Позвольте мне предложить вам более всеобъемлющее осуществление.

конфигурация multer в 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)
    }
}));

посмотреть

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

загрузить профиль pic logic в контроллере пользователей

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

попробуй такое

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/


использовать этой пример, он использует функцию Firebase cloud и хранилище firebase для загрузки файла, но вы можете использовать его для чего угодно,он использует express-multipart-file-parser и работает как шарм вышеуказанная ссылка просто отлично работает, я тестировал этот код и толкнул его в РЕПО для вас, ребята.Просто добавьте свою конфигурацию и все.