javascript - NodeJS Multer 不工作

标签 javascript html node.js express multer

我尝试使用 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");
});

公共(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 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' POST 调用 Controller 中的 uploadProfilePic

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

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

关于javascript - NodeJS Multer 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29490833/

相关文章:

javascript - 使用 JavaScript 发送 HTTP 请求

javascript - 如何在 javascript 中给出 !important

javascript - 具有 100vw 和 100vh 的 SVG.JS 响应矩形

javascript - 向下滚动时导航栏更改背景,但向上滚动时不会变回

node.js - 在 Eclipse 中安装 node.js 模块

Javascript console.log 不读取数组未定义

javascript - 从内联javascript获取e参数

html - 如何从 Twenty Twelve 主题中删除响应代码

javascript - 按需从 lodash 加载模块

node.js - Node sqlite node-gyp 构建错误 : no member named 'ForceSet' in 'v8::Object'