<template>
<div class="clearfix">
<a-upload
listType="picture-card"
:fileList="fileList"
@preview="handlePreview"
:beforeUpload="beforeUpload"
@change="handleChange"
:remove="handleRemove"
>
<div v-if="fileList.length < imgLength">
<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>
import axios from 'axios'
import { imagePage,imageDelete } from '@/api/file'
export default {
name: 'PictureUpload',
props: {
imgLength: {
type: [Number, String],
default: 10
}
},
data() {
return {
previewVisible: false,
previewImage: '',
uid: 0,
removeIds: [],
URL: process.env.VUE_APP_API_BASE_URL,
token: this.$store.getters.token,
fileList: []
}
},
mounted() {},
methods: {
handleCancel () {
this.previewVisible = false
},
handlePreview (file) {
this.previewImage = file.url || file.thumbUrl
this.previewVisible = true
},
handleChange({ fileList }) {
//debugger
//this.fileList = fileList
},
getFile(obj={}) {
//回顯獲取圖片list
const data={}
for(let key in obj){
if(!data.eqs){
data.eqs=[]
}
const eq={}
eq.key=key
eq.val=obj[key]
data.eqs.push(eq)
}
let vm = this
vm.fileList.length=0
imagePage({...data,size:-1}).then(res=>{
res.data.records.map(res => {
const file = {}
file.uid = res.id
file.name = res.oldFileName
file.url = vm.URL + '/static-image/' + res.filePathName
vm.fileList.push(file)
})
})
},
handleDelete() {
//刪除圖片
if (this.removeIds.length > 0) {
imageDelete(this.removeIds.join(',')).then(res => {
console.log(res)
})
}
},
handleSave(attachType, relationId) {
let vm = this
return new Promise((resolve, reject) => {
const formData = new FormData()
let index = 0
vm.fileList.forEach(file => {
if (file.size) {
formData.append('file', file)
index++
}
})
formData.append('imageType', attachType || '')
formData.append('relationId', relationId || '')
if (formData.get('file') == null) {
if (vm.removeIds.length > 0) {
vm.handleDelete()
}
return resolve()
}
axios({
method: 'post',
url: vm.URL + '/file/image/batchUpload',
data: formData,
headers: {
Authorization: vm.token
}
})
.then(res => {
if (res.data.code !== 0) {
reject(res.data.msg)
} else {
vm.handleDelete()
resolve(res.data)
}
})
.catch(err => {
reject(err)
})
})
},
handleRemove(file) {
if (!file.size) {
this.removeIds.push(file.uid)
}
const index = this.fileList.indexOf(file)
const newFileList = this.fileList.slice()
newFileList.splice(index, 1)
this.fileList = newFileList
},
beforeUpload(file) {
let src = ''
let cm = this
getBase64(file, imageUrl => {
src = imageUrl
file.url = src
cm.fileList = [...cm.fileList, file]
})
return false
if (this.filelength != 0 && this.filelength == this.fileList.length) {
return this.$message.warning('最高只能上傳' + this.filelength + '個附件')
}
this.fileList = [...this.fileList, file]
console.log(this.fileList)
return false
}
}
}
</script>
<style lang="less" scoped></style>