1.
<template> <!--说明:发送请求的接口应该写在api/users或api/companyInfo中,请求方式为form-data类型--> <el-upload class="avatar-uploader" ref="uploadPicture" action="#" list-type="picture-card" :auto-upload="true" :show-file-list="false" :file-list="fileList" :on-success="handleAvatarSuccess" :http-request="handleRequest" :on-change="changeFileStatus"> <img v-if="imgUrl" :src="imgUrl" class="avatar userimgPic"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </template>
export default { name: 'UploadPic', //父组件传过来的属性 props: { // 图片的地址 'profile': { type: String, default: '' }, // 图片的大小限制,单位kb 'sizeLimit': { type: Number, default: 1024 }, // 图片类型,数组,可选字符串:'image/jpeg' ,'image/jpg' ,'image/png' 'imgType': { type: Array, default: () => ['image/jpeg', 'image/jpg', 'image/png'] } }, data () { return { imgList: [], imgUrl: '', requestApi: {}, fileList: [] } }, computed: { imgUrlTmp () { return this.profile } }, watch: { profile: { immediate: true, handler: function (val) { if (val !== '') { this.getProfileBuffer(val) } } } }, created () { this.requestApi = { ...COMPINFOAPI, ...USERAPI } }, methods: { /** * 不使用默认的发送方式,自定义发送请求 * // 上传图片的接口是单独的 * */ handleRequest (file) { this.$emit('upload-pic-result', file) file.onSuccess() }, /** * 拿到图片地址后用get请求获取图片 * */ getProfileBuffer (val) { let self = this // 对获取到的图片后台地址截取名字 let imgUrl = val.lastIndexOf('\') let url = val.slice(imgUrl + 1) // 因为直接访问服务器地址无法正确显示图片,所以再次发送get请求获取图片 USERAPI.getPic(url).then(res => { if (res.status === 200) { let data = new Blob([res.data], { type: 'image/png' }) let url = window.URL.createObjectURL(data) self.imgUrl = url // window.URL.revokeObjectURL(url) } }) }, handleAvatarSuccess (res, file) {
//预览上传的图片的效果 this.imgUrl = URL.createObjectURL(file.raw) }, /** * 添加文件时也会触发状态改变,用于做大小和文件类型的判断 * */ changeFileStatus (file, fileList) { let self = this this.imgList = fileList if (fileList.length > 1) { fileList.splice(0, fileList.length - 1) } if (file.raw.name) { // const isIMAGE = file.raw.type.indexOf(this.imgType) let isIMAGE = false this.imgType.forEach((item) => { if (file.raw.type === item) { isIMAGE = true } }) let limit = this.sizeLimit === 1024 ? 1024 : this.sizeLimit const isLt1M = file.raw.size / 1024 < limit if (!isIMAGE) { self.$message.error('上传文件只能是图片格式!') } if (!isLt1M) { self.$message.error(`上传文件大小不能超过 ${this.sizeLimit}kB!`) } if (isIMAGE && isLt1M) { this.imgUrl = URL.createObjectURL(file.raw) } else { let delFile let itemIndex fileList.forEach((item, index) => { if (item.uid === file.uid) { delFile = item itemIndex = index } }) if (delFile) { fileList.splice(itemIndex, 1) } return false } return false } } }, beforeDestroy () { if (this.imgUrl !== '') { window.URL.revokeObjectURL(this.imgUrl) } } }