详解nodejs实现本地上传图片并预览功能(express4.0+)

2020-06-17 06:31:20易采站长站整理

Express为:4.13.1  multyparty: 4.1.2

代码主要实现本地图片上传到nodejs服务器的文件下,通过取图片路径进行图片预览

写在前面:计划实现图片上传预览功能,但是本地图片上传所获得路径为 C:fakepath”+文件名的形式,得不到文件真实路径,所以无法直接预览,于是采用将图片上传至服务器,传回服务器路径,实现预览。前端采用通过ajax方式上传文件,使用FormData进行ajax请求  ,nodejs端采用multiparty模块

相关查看文档:

通过Ajax方式上传文件,使用FormData进行Ajax请求

node-multiparty github

FormData – Web APIs | MDN

部分代码:


<form name='picForm' action = "javascript:;"method="post" encype = "multipart/form-data" >
<input type="file" id="test" id="j_imgfile">
</form>
<div>
<img src="" id="j_imgPic">
</div>

 js中采用change事件,即当选完图片时就发送ajax请求


$('#j_imgfile').on('change',function(){
// 判断上传文件类型
var objFile = $('#j_imgfile').val();
var objType = objFile.substring(objFile.lastIndexOf(".")).toLowerCase();
var formData = new FormData(document.forms.namedItem("picForm"));
console.log(objType);
if(!(objType == '.jpg'||objType == '.png'))
{
alert("请上传jpg、png类型图片");
return false;
}else{
$.ajax({
type : 'post',
url : '/uploadUserImgPre',
data: formData ,
processData:false,
async:false,
cache: false,
contentType: false,
success:function(re){
re.imgSrc = re.imgSrc.replace('public','');
re.imgSrc = re.imgSrc.replace(//g,'/');
$('#j_imgPic').attr('src',re.imgSrc);
},
error:function(re){
console.log(re);
}
});
}
});

 nodejs app.js里代码


app.post('/uploadUserImgPre',routes.users.uploadUserImgPre);

routes/users.js 里代码


exports.uploadUserImgPre = function(req, res, next) {
//生成multiparty对象,并配置上传目标路径
var form = new multiparty.Form({uploadDir: './public/files/images'});
form.parse(req, function(err, fields, files) {
var filesTmp = JSON.stringify(files);

if(err){
console.log('parse error: ' + err);
} else {
testJson = eval("(" + filesTmp+ ")");
console.log(testJson.fileField[0].path);
res.json({imgSrc:testJson.fileField[0].path})
console.log('rename ok');
}
});
}