1.在项目目录中,通过npm install multiparty进行安装必要组件
npm install multiparty --save-dev
2.app.js中添加
app.use(bodyParser({uploadDir:'./uploadtemp'}));//设置上传临时文件夹
//在与app.js同目录下创建uploadtemp文件夹
3.index.js中
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
//-------文件上传------
router.post('/imgupload',function(req,res){
//-----------------------------------------
var form = new multiparty.Form();
//设置编辑
form.encoding = 'utf-8';
//设置文件存储路径
form.uploadDir = "./uploadtemp/";
//设置单文件大小限制
form.maxFilesSize = 2 * 1024 * 1024;
//form.maxFields = 1000; 设置所以文件的大小总和
form.parse(req, function(err, fields, files) {
for(var key in files){
console.log(key+'=='+files[key]);
for(var kk in files[key][0].headers){
console.log(kk+'==='+files[key][0].headers[kk]);
}
}
file1 = files['myimg'];
paraname = file1[0].fieldName; //参数名myimg
originalFilename = file1[0].originalFilename; //原始文件名
tmpPath = file1[0].path;//uploads\mrecQCv2cGlZbj-UMjNyw_Bz.txt
fileSize = file1[0].size; //文件大小
var timestamp=new Date().getTime(); //获取当前时间戳
newPath= './public/images/'+timestamp+originalFilename;
var fileReadStream = fs.createReadStream(tmpPath);
var fileWriteStream = fs.createWriteStream(newPath);
fileReadStream.pipe(fileWriteStream); //管道流
fileWriteStream.on('close',function(){
console.log('copy over');
});
/*
function writeFile(data){
fs.writeFile(newPath,data,function(error){
if(error){
throw error;
}else{
console.log("文件已保存");
}
});
}
fs.readFile(tmpPath,'ascii',function(err, data) {
if (err) {
console.log("读取失败");
} else {
writeFile(data);
}
});
*/
//重命名为真实文件名
/*
fs.rename(tmpPath, newPath, function(err) {
if(err){
console.log('rename error: ' + err);
} else {
console.log('rename ok');
}
});
*/
//删除临时文件夹中的文件
//fs.unlinkSync(tmpPath);
});
//-----------------------------------------
res.send('上传完成');
});
4.客户端
<html>
<head>
<link rel="stylesheet" href='/flex.css'/>
</head>
<body>
<% include header %>
<form enctype="multipart/form-data" method='post' action='/imgupload'>
<table border='1' align='center'>
<tr>
<td>图片上传</td>
</tr>
<tr>
<td>
<input type='file' name='myimg'/>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='上传'/>
</td>
</tr>
</table>
</form>
<% include footer%>
</body>
</html>
如果uploads不是临时文件夹再次安装:
D:\www\nodejs2\blog>npm install body-parser --save-dev
DEMO下载地址:https://dwz.cn/fgXtRtnu