NodeJS Multer不工作 [英] NodeJS Multer is not working

查看:144
本文介绍了NodeJS 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); //表单字段
console.log(req。文件); //表单文件
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 =postenctype =multipart / form-data>
< input id =filetype =file/>
< button type =submit> test< / button>
< / form>
< / body>
< / html>

当我点击提交按钮时,我的NodeJS控制台日志:

 C:\Program Files\\\
odejs\\\
ode.exeserver.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 + 。$)
},
onFileUploadData:function(file,data){
console.log(data.length +'of'+ file.fieldname +'arrival')
}
onFileUploadComplete:function(file){
console.log(file.fieldname +'upload to'+ file.path)
}
}));



查看



 < form id =uploadProfilePicFormenctype =multipart / form-dataaction =/ user / profile_pic / uploadmethod =post> 
< input type =filemultiple =multipleid =userPhotoInputname =userPhotoaccept =image / */>
< input type =submitname =submitvalue =Upload>
< / form>

终点' / user / profile_pic_upload 'POST调用 uploadProfilePic 在控制器



上传用户控制器中的配置文件图片逻辑



  uploadProfilePic = function(req,res){
//获取文件的临时位置
var tmp_path = req.files.userPhoto.path;
//设置文件实际存在的位置
var target_path ='/ Users / narendra / Documents / Workspaces / NodeExpressWorkspace / MongoExpressUploads / profile_pic /'+ req.files.userPhoto.name;
//将文件从临时位置移动到预定位置
fs.rename(tmp_path,target_path,function(err){
if(err)throw err;
/ /删除临时文件,以便明确设置临时上载目录不会被填充不需要的文件
fs.unlink(tmp_path,function(){
if(err){
throw err ;
} else {
var profile_pic = req.files.userPhoto.name;
//使用profile_pic来执行其他的东西,如更新DB或写入渲染逻辑,
};
});
});
};


I tried to file upload with NodeJS + ExpressJS + Multer but does not work well.

My ExpressJS Version is 4.12.3

this is my source

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>

My NodeJS Console Log when I click Submit Button:

"C:\Program Files\nodejs\node.exe" server.js
start 5000
{}

on NodeJS Console, there is empty object at req.files Is some problem on my source?

解决方案

I don't see you calling any API to upload file on click of submit button. Let me give you move comprehensive implementation.

multer config in 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)
    }
}));

View

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

End point '/user/profile_pic_upload' POST calls uploadProfilePic in controller

Upload profile pic logic in users 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.
             };
            });
        });
};

这篇关于NodeJS Multer不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆