1 回答
TA贡献1847条经验 获得超7个赞
Multer is a node.js middleware for handling multipart/form-data for koa.
multer wrapper for koa's middleware.
至于怎么上传文件还不是很懂。
但是我们用另一种方法:上传base64,后台再处理base64
var readFileIntoDataUrl = function (fileInfo) {
// var loader = $.Deferred(),
// fReader = new FileReader();
// fReader.onload = function (e) {
// loader.resolve(e.target.result);
// };
// fReader.onerror = loader.reject;
// fReader.onprogress = loader.notify;
// fReader.readAsDataURL(fileInfo);
// return loader.promise();
var loader = $.Deferred(),
fReader = new FileReader();
fReader.onload = function (e) {
$.ajax({
url: '/base64',
method: 'post',
data: {img: e.target.result}
}).done(function(msg) {
loader.resolve(msg.url);
});
};
fReader.onerror = loader.reject;
fReader.onprogress = loader.notify;
fReader.readAsDataURL(fileInfo);
return loader.promise();
};
....
async function a(dataBuffer,type) {
var name = Date.now() +'.' + type;
var url = __dirname + '/app/public/uploads/'+name
return new Promise(function(resolve, reject) {
fs.writeFile(url, dataBuffer, function(err) {
if(err){
reject(err);
}else{
resolve({
url: '/uploads/'+name
});
}
});
});
}
router.post('/base64', async function(ctx, next) {
var imgData = ctx.request.body.img;
//过滤data:URL
var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
var type = imgData.replace(/data:image\/([^;]+).*/i,'$1');//取类型
var dataBuffer = new Buffer(base64Data, 'base64');
var img = await a(dataBuffer,type);
console.log(img);
return ctx.body = img;
});
...
添加回答
举报