<template>
<div class="clearfix">
<a-upload
:headers="headers"
:action="fileurl"
list-type="picture-card"
:file-list="fileList"
:before-upload="beforeUpload"
@preview="handlePreview"
@change="handleChange"
>
<div v-if="fileList.length < imgNum">
<a-icon type="plus" />
<div class="ant-upload-text">
上传图片
</div>
</div>
</a-upload>
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
<img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</div>
</template>
<script>
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
export default {
props: {
msgVal: {
type: String,
default: ""
}
},
data() {
return {
imgNum:1,
headers: {
'token': localStorage.getItem('token'),
},
fileurl:'http://192.168.18.188:9103'+"/file/upload",
previewVisible: false,
previewImage: '',
fileList: []
};
},
methods: {
handleCancel() {
this.previewVisible = false;
},
async handlePreview(file) {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
},
handleChange({ fileList }) {
this.fileList = fileList; //fileList[0].response.data.fjurl//后台只需要这个地址/upload/2021-04-16/jyzxx.png
this.$emit('fileimgUrl', fileList[0].response.data.fjurl)
},
beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
this.$message.error('请上传jpg/png格式图片!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('图片大小不得超出2MB!');
}
return isJpgOrPng && isLt2M;
},
},
};
</script>
<style scoped>
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
使用:
<upload-img @fileimgUrl="fileimgUrl" :msg-val="msg"></upload-img>
<!-- -->
fileimgUrl(value){
//得到后台传过来的地址
console.log(value)
}
假如在编辑的时候,后台返回了地址:http://192.168.18.188:9103/upload/2021-04-16/jyzxx.png,可直接给fileList赋值
fileList: [
{
uid: '-1',
name: 'image.png',
status: 'done',
url: msg,
},
下面为传到后台返回的:
写的不好,可留言指正,互相学习!