element 组件
<el-upload
action="#"
name="uploadFile"
class="avatar-uploader"
:auto-upload="true"
ref="upload"
:drag="true"
accept="image/*"
:show-file-list="false"
:http-request="onUploadImage"
:before-upload="beforeUpload">
<img v-if="companyData.companyImage" :src="companyData.companyImage" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<div v-if="!companyData.companyImage">图片上传支持JPG,PNG格式</div>
</el-upload>
2.上传之前对图片进行限制
beforeUpload(file) {
const isPic = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isPic) {
Message.error('上传文件只能是 jpg、jpeg、png 格式!');
}
if (!isLt5M) {
Message.error('上传文件大小不能超过 5MB!');
}
return isPic && isLt5M;
},
3.上传
onUploadImage(item) {
//修改图片接口
uploadFile(item.file).then(res => {
//修改图片成功回显
this.companyData.companyImage = res.data.url
//修改后的图片 包括机构信息进行上传更新
updateCompanyInfo(this.companyData).then(response => {
Message.success('修改成功')
})
})
},
4.图片接口进行new FormData处理
export function uploadFile(file, fileType) {
const companyId = session.get('companyId')
return new Promise((reslove) => {
reslove()
}).then(() => {
const fd = new FormData()
if (!fileType) {
fd.append('uploadFile', file, fileType)
} else {
fd.append('uploadFile', file)
}
return request({
method: 'post',
url: `api/mdp/v2/company/${companyId}/file`,
timeout: 20000,
data: fd
})
})
}