乐趣区

egg(70)–egg之前端图片批量上传插件webuploader

引入 webuploader
<link rel=”stylesheet” type=”text/css” href=”/public/admin/webuploader/css/webuploader.css”>
<link rel=”stylesheet” type=”text/css” href=”/public/admin/webuploader/css/diyUpload.css”>
<script type=”text/javascript” src=”/public/admin/webuploader/js/webuploader.html5only.min.js”></script>
<script type=”text/javascript” src=”/public/admin/webuploader/js/diyUpload.js”></script>
前端
app/view/admin/goods/add.html
<div role=”tabpanel” class=”tab-pane” id=”photo”>
<div id=”photoLib” class=”photoLib”></div>
<div id=”photoList”>
</div>
</div>
$(function(){
var photoStr = “”;
$(“#photoLib”).diyUpload({
url:’/admin/goods/goodsUploadPhoto’,
success:function(response){
photoStr = ‘<input type=”hidden” name=”goods_image_list[]” value=’+response.link+’ />’;
$(“photoList”).append(photoStr);
},
error:function(err){
console.log(err)
}
})
})
后台
router.js
router.post(‘/admin/goods/goodsUploadPhoto’, controller.admin.goods.goodsUploadPhoto);
controller
app/controller/admin/goods.js
async goodsUploadPhoto() {
// 实现图片上传
let parts = this.ctx.multipart({autoFields: true});
let files = {};
let stream;
while ((stream = await parts()) != null) {
if (!stream.filename) {
break;
}
let fieldname = stream.fieldname; //file 表单的名字

// 上传图片的目录
let dir=await this.service.tools.getUploadFile(stream.filename);
let target = dir.uploadDir;
let writeStream = fs.createWriteStream(target);

await pump(stream, writeStream);

files=Object.assign(files,{
[fieldname]:dir.saveDir
})

// 生成缩略图
this.service.tools.jimpImg(target);

}
// 图片的地址转化成 {link: ‘path/to/image.jpg’}

this.ctx.body={link: files.file};
}
效果

退出移动版