图片上传 可多张
组件部分
<template>
<div class="clearfix">
<a-upload list-type="picture-card" :multiple="true" @preview="handlePreview" :file-list="fileList1"
:customRequest="uploadImage" :remove="deleteImage">
<div v-if="fileList1.length < fileListNum">
<a-icon type="plus" />
<div class="ant-upload-text">
{{ fileListName }}
</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>
import axios from 'axios'
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: {
fileListNum: {
type: Number,//上传数量
},
fileListName: {
type: String,//内容提示
},
fileList: {
type: String,//图片列表 字符串
}
},
data() {
return {
previewVisible: false,
previewImage: '',
fileList1: [],
fielListName: '',
};
},
watch: {
fileList: {
handler(newVal, oldVal) {
console.log('传入图片', this.fileList);
if (this.fileList.length > 0) {
this.fileList1 = this.fileList.split(',').map(i => {
return {
name: '图片',
status: 'done',
uid: i,
url: i
}
})
} else {
this.fileList1 = []
}
},
deep: true,
immediate: true
},
},
mounted() {
},
methods: {
handleCancel() {
this.previewVisible = false;
},
uploadImage(file) {
const formData = new FormData();
formData.append("uploadFile", file.file);
this.saveFile(formData);
},
deleteImage(e) {
let index = this.fileList1.findIndex((i) => {
return i.uid === e.uid
})
this.fileList1.splice(index, 1)
this.$emit('update:fileList', this.fileList1.map(i => {
return i.url
}).toString(','));
console.log(this.fileList1.length, this.fileListNum, index, e, this.fileList1);
},
saveFile(formData) {
axios.post('请求接口', formData)
.then((res) => {
if (res.data.code == 200) {
// 存入列表
this.fileList1.push({
uid: new Date().getTime(),
name: '课程封面.png',
status: "done",
url: res.data.data,
});
this.previewImage = res.data.data
this.$emit('update:fileList', this.fileList1.map(i => {
return i.url
}).toString(','));
console.log(this.fileList1.map(i => {
return i.url
}).toString(','));
} else {
this.$message.error("图片要小于500kb,请压缩后上传");
}
})
.catch(function (error) {
// console.log(error);
});
},
async handlePreview(file) {
// console.log(file);
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
},
handleChange({ fileList1 }) {
// console.log({ fileList1 });
if (fileList1.length <= this.fileListNum) {
this.fileList1 = fileList1;
}
},
},
};
</script>
页面部分 引入
<Upload class="upload" :fileListNum="fileListNum" :fileListName="fileListName"
:fileList.sync="form.imageUrl" ref="uploadImg"></Upload>
视频 上传 与图片上传类似 区别预览播放