tips:调用方法时,请try...catch...
1.multiparty上传文件
1 function uploadfile(request) { 2 return new Promise(function(resolve, reject){
var multiparty=require('multiparty'); //引入依赖 3 var form = new multiparty.Form(); 4 //设置编码 5 form.encoding = 'utf-8'; 6 //设置文件存储路径 7 form.uploadDir = "static/files/"; 8 //设置单文件大小限制 9 form.maxFilesSize = 20 * 1024 * 1024; 10 //form.maxFields = 1000; 设置所有文件的大小总和 11 //生成临时文件 12 form.parse(request, function(err, fields, files) { 13 if (err){ 14 console.log(err); 15 reject({success:false}) 16 } else { 17 console.log(files); //文件对象
console.log(fields); //附加字段参数 18 if (!files||!files.file||files.file.length==0) { 19 reject({success:false}); 20 } 21 resolve({success:true,path:files.file[0].path}) 22 } 23 }) 24 }) 25 }
2.base64上传图片
function uploadfilebase64(request) { return new Promise(function(resolve, reject){
let fs =require('fs')
let uuidV1=require('uuid/v1') let imgData=request.body.imgData //前端以application/json形式传递 let base64Data = imgData.replace(/^data:image\/png;base64,/,""); let dataBuffer = new Buffer(base64Data, 'base64'); let uuid = uuidV1(); let filePath = "static/files/"+uuid+".png";//定义文件路径及名称,无论是jpg还是png的都可以保存成png fs.writeFile(filePath, dataBuffer, function(err) { if(err){ console.log(err); reject({success:false}) }else{ resolve({success:true,path:filePath}) } }); }) }
以上若有问题欢迎指正......
------------恢复内容结束------------