需求如上图:多个图片上传,我用的是element-ui自带的上传组件<el-upload></el-upload>
1 <el-upload 2 v-if="$route.params.mode === 'add'" 3 class="upload-demo" 4 :limit="1" 5 :on-exceed="handleExceed" 6 :on-preview="handlePreview" 7 :data="uploadParams(subItem)" 8 :action="uploadUrl()" 9 :on-remove="function(file, fileList){ return handleRemove(file, fileList, subItem) }" 10 :on-success="function(res, file, fileList){ return handleSuccess(res, file, fileList, subItem) }" 11 > 12 <el-button size="small" type="text">点击上传</el-button> 13</el-upload>
1 computed: { 2 uploadParams() { 3 return subItem => { 4 let params = { 5 weiyibianhao: this.shipCode, 6 questionNo: subItem.questionNo 7 }; 8 return params; 9 }; 10 } 11 },
1 // 上传相关 2 uploadUrl() { 3 return '/sdkseaunion/inspectApi/uploadQuestionImage'; 4 }, 5 handleExceed(files, fileList) { 6 this.$message.warning('只能上传一张图片'); 7 }, 8 handlePreview(file) { 9 this.picUrl = file.response.data.fileUrl; 10 this.isPicView = true; 11 }, 12 beforeAvatarUpload(file) { 13 const isJPG = file.type === 'image/jpeg'; 14 const isPNG = file.type === 'image/png'; 15 const isLt5M = file.size / 1024 / 1024 < 5; 16 if (!isJPG || !isPNG) { 17 this.$message.error('上传头像图片只能是jpg格式或者png格式!'); 18 } 19 if (!isLt5M) { 20 this.$message.error('上传头像图片大小不能超过 5MB!'); 21 } 22 return isJPG && isLt5M; 23 }, 24 handleRemove(file, fileList, subItem) { 25 $http.post('/sdkseaunion/inspectApi/delQuestionImage', { 27 weiyibianhao: this.shipCode, 28 questionNo: subItem.questionNo 29 }).then(rspData => { 31 this.$message({ 32 type: 'success', 33 message: '删除成功!' 34 }); 35 }); 36 }, 37 handleSuccess(res, file, fileList, subItem) { 38 // console.log('上传成功'); 39 },
图片预览html:
1 <!-- 图片预览 --> 2 <div class="model-wrapper" v-if="isPicView"> 3 <div class="model"> 4 <img :src="picUrl" /> 5 <i class="icon-close" @click="isPicView = false"></i> 6 </div> 7 <div class="mask"></div> 8 </div>
图片预览css:
/* 模态弹窗 */ .model-wrapper { .model { position: fixed; left: 50%; top: 50%; z-index: 10; 1200px; height: 740px; background: #000; transform: translate(-50%, -50%); box-shadow: 0 12px 24px 0 rgba(28, 31, 33, 0.1); transition: all 0.2s; -webkit-transition: all 0.2s; display: flex; align-items: center; img { 1200px; height: 740px; object-fit: contain; } .icon-close { display: block; position: absolute; right: 4px; top: 7px; 40px; height: 40px; background: url('../../assets/images/icon-close.png') no-repeat left top; background-size: 100%; } } .mask { position: fixed; left: 0; top: 0; 100%; height: 100%; opacity: 0.6; z-index: 1; background: #000; } }