项目里面涉及图片上传的功能,要图片可以预览,上传的时候图片大了要做压缩
- 图片上传以及预览
<Form-item label="图片详情" prop="imageUrl">
<el-upload
class="avatar-uploader"
:action="action"
:headers="headers"
list-type="picture-card"
name="file"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:before-upload = "beforeUpload"
v-model="formItem.imageUrl"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="formItem.imageUrl">
</el-dialog>
</Form-item>
const imageConversion = require("image-conversion");
export default {
data(){
dialogVisible: false,
formitem:{
imageUrl: '' 单张图片地址
},
allImgUrl: []
}
methods: {
handleSuccess(res) {
const { code, data } = res
if (code == '0000' && data.url) {
this.allImgUrl.push(data.url)
}
this.formItem.imageUrl = data.url
},
handlePictureCardPreview(file) {
this.formItem.imageUrl = file.url;
this.dialogVisible = true;
},
handleRemove(file, fileList) {
let removeUrl = file.response.data.url
this.allImgUrl = this.allImgUrl.filter(item => item != removeUrl)
},
beforeUpload(file) {
return new Promise((resolve, reject) => {
let isLt2M = file.size / 1024 / 1024 < 2
if (isLt2M) {
resolve(file)
}
imageConversion.compressAccurately(file, 400).then(res => {
resolve(res)
})
})
},
}
}
安装image-conversion包
- npm install image-conversion --save 或者 yarn add image-conversion – save
- 这样就实现了图片的自动压缩功能,这个组件还有一些其他功能,使用的时候如果有其他需求,可以看下文档
- 网址
element-ui官网图片上传upload
|