[update] 文件上传组件-文件预览的优化

This commit is contained in:
fengchenchen
2021-09-06 13:41:30 +08:00
parent 8ba578030c
commit c7af6d8d35
2 changed files with 305 additions and 294 deletions
+303 -292
View File
@@ -17,11 +17,12 @@
:class="{'uploadty-disabled':disabled}"> :class="{'uploadty-disabled':disabled}">
<template> <template>
<div v-if="isImageComp"> <div v-if="isImageComp">
<a-icon type="plus" /> <a-icon type="plus"/>
<div class="ant-upload-text">{{ text }}</div> <div class="ant-upload-text">{{ text }}</div>
</div> </div>
<a-button v-else-if="buttonVisible"> <a-button v-else-if="buttonVisible">
<a-icon type="upload" />{{ text }} <a-icon type="upload"/>
{{ text }}
</a-button> </a-button>
</template> </template>
</a-upload> </a-upload>
@@ -30,333 +31,343 @@
<script> <script>
import Vue from 'vue' import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types' import {ACCESS_TOKEN} from '@/store/mutation-types'
import { getFileAccessHttpUrl } from '@/api/manage' import {getFileAccessHttpUrl} from '@/api/manage'
import { getFileInfo } from '@/api/api' import {getFileInfo} from '@/api/api'
const Base64 = require('js-base64').Base64
const FILE_TYPE_ALL = 'all' const Base64 = require('js-base64').Base64
const FILE_TYPE_IMG = 'image'
const FILE_TYPE_TXT = 'file' const FILE_TYPE_ALL = 'all'
const uidGenerator=()=>{ const FILE_TYPE_IMG = 'image'
return '-'+parseInt(Math.random()*10000+1,10) // const FILE_TYPE_TXT = 'file'
} const uidGenerator = () => {
export default { return '-' + parseInt(Math.random() * 10000 + 1, 10)
name: 'JUpload', }
data(){ export default {
return { name: 'JUpload',
uploadAction:window._CONFIG['domianURL']+'/sys/common/upload', data() {
headers:{}, return {
fileList: [], uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
newFileList: [], headers: {},
uploadGoOn:true, fileList: [],
} newFileList: [],
uploadGoOn: true,
}
},
props: {
text: {
type: String,
required: false,
default: '点击上传'
}, },
props: { fileType: {
text: { type: String,
type: String, required: false,
required: false, default: FILE_TYPE_ALL
default: '点击上传'
},
fileType: {
type: String,
required: false,
default: FILE_TYPE_ALL
},
/*这个属性用于控制文件上传的业务路径*/
bizPath: {
type: String,
required: false,
default: 'temp'
},
value: {
type: [String, Array],
required: false
},
// update-begin- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
disabled: {
type: Boolean,
required: false,
default: false
},
// update-end- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
//此属性被废弃了
triggerChange: {
type: Boolean,
required: false,
default: false
},
/**
* update -- author:lvdandan -- date:20190219 -- for:Jupload组件增加是否返回url,
* true:仅返回url
* false:返回fileName filePath fileSize
*/
returnUrl: {
type: Boolean,
required: false,
default: true
},
/**
* 仅返回文件id
* true 仅返回文件id
* false 返回reurl
* */
returnId:{
type:Boolean,
required:false,
default: false
},
number: {
type: Number,
required: false,
default: 0
},
buttonVisible: {
type: Boolean,
required: false,
default: true
},
}, },
watch:{ /*这个属性用于控制文件上传的业务路径*/
value:{ bizPath: {
immediate: true, type: String,
handler() { required: false,
let val = this.value default: 'temp'
if (val instanceof Array) { },
if(this.returnUrl){ value: {
this.initFileList(val.join(',')) type: [String, Array],
}else{ required: false
this.initFileListArr(val) },
} // update-begin- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
disabled: {
type: Boolean,
required: false,
default: false
},
// update-end- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
//此属性被废弃了
triggerChange: {
type: Boolean,
required: false,
default: false
},
/**
* update -- author:lvdandan -- date:20190219 -- for:Jupload组件增加是否返回url,
* true:仅返回url
* false:返回fileName filePath fileSize
*/
returnUrl: {
type: Boolean,
required: false,
default: true
},
/**
* 仅返回文件id
* true 仅返回文件id
* false 返回reurl
* */
returnId: {
type: Boolean,
required: false,
default: false
},
number: {
type: Number,
required: false,
default: 0
},
buttonVisible: {
type: Boolean,
required: false,
default: true
},
},
watch: {
value: {
immediate: true,
handler() {
let val = this.value
if (val instanceof Array) {
if (this.returnUrl) {
this.initFileList(val.join(','))
} else { } else {
this.initFileList(val) this.initFileListArr(val)
} }
} else {
this.initFileList(val)
} }
} }
}
},
computed: {
//透传给下级组件的事件,需要排除本组件使用的change事件
childListeners() {
// const vm = this
let result = Object.assign({},
this.$listeners,
)
delete result.change
return result
}, },
computed:{ isImageComp() {
//透传给下级组件的事件,需要排除本组件使用的change事件 return this.fileType === FILE_TYPE_IMG
childListeners() {
const vm = this
let result = Object.assign({},
this.$listeners,
)
delete result.change
return result
},
isImageComp(){
return this.fileType === FILE_TYPE_IMG
},
complistType(){
return this.fileType === FILE_TYPE_IMG?'picture-card':'text'
},
}, },
created(){ complistType() {
const token = Vue.ls.get(ACCESS_TOKEN) return this.fileType === FILE_TYPE_IMG ? 'picture-card' : 'text'
//---------------------------- begin 图片左右换位置 -------------------------------------
this.headers = {'X-Access-Token':token}
this.containerId = 'container-ty-'+new Date().getTime()
//---------------------------- end 图片左右换位置 -------------------------------------
}, },
methods:{ },
initFileListArr(val){ created() {
if(!val || val.length==0){ const token = Vue.ls.get(ACCESS_TOKEN)
this.fileList = [] //---------------------------- begin 图片左右换位置 -------------------------------------
return this.headers = {'X-Access-Token': token}
} this.containerId = 'container-ty-' + new Date().getTime()
for(var a=0;a<val.length;a++){ //---------------------------- end 图片左右换位置 -------------------------------------
this.fileList.forEach((item)=>{ },
if (item.url === val[a]){ methods: {
item.uid = uidGenerator() initFileListArr(val) {
item.response.status = 'done' if (!val || val.length === 0) {
} this.fileList = []
}) return
} }
}, for (let a = 0; a < val.length; a++) {
async initFileList(paths){ this.fileList.forEach((item) => {
if(!paths || paths.length === 0){ if (item.url === val[a]) {
this.fileList = [] item.uid = uidGenerator()
return item.response.status = 'done'
} }
let arr = paths.split(',') })
// 返回路径的时候,对路径进行操作,取出所属id }
if(!this.returnId && arr.length > 0) { },
const newArr = [] async initFileList(paths) {
arr.map(item => { if (!paths || paths.length === 0) {
let itemArr = item.split('/') this.fileList = []
newArr.push(itemArr[itemArr.length - 1]) return
}) }
arr = newArr let arr = paths.split(',')
} // 返回路径的时候,对路径进行操作,取出所属id
const fileList = [] if (!this.returnId && arr.length > 0) {
for (let a = 0; a < arr.length; a++) { const newArr = []
// 获取每一个文件的信息,组成fileList arr.map(item => {
let itemArr = item.split('/')
newArr.push(itemArr[itemArr.length - 1])
})
arr = newArr
}
const fileList = []
for (let a = 0; a < arr.length; a++) {
// 获取每一个文件的信息,组成fileList
// 突然想判断现在的fileList 中是否是历史的信息,如果是的话则先进行匹配
let isHistory = this.fileList.find(file => file.response.status === 'history' && (file.response.result || {}).id === arr[a])
console.log("isHistory===", isHistory)
if (isHistory) {
fileList.push(isHistory)
} else {
const fileObj = await this.getFileInfo(arr[a]) const fileObj = await this.getFileInfo(arr[a])
const url = getFileAccessHttpUrl(arr[a]) const url = getFileAccessHttpUrl(arr[a])
fileList.push({ fileList.push({
uid: uidGenerator(), uid: uidGenerator(),
name: fileObj.fileName, name: (fileObj || {}).fileName,
status: 'done', status: 'done',
url: url, url: url,
response: { response: {
status: 'history', status: 'history',
message: arr[a] message: arr[a],
result: fileObj
} }
}) })
} }
this.fileList = [...fileList] }
this.fileList = [...fileList]
}, },
handlePathChange(){ handlePathChange() {
let uploadFiles = this.fileList let uploadFiles = this.fileList
let path = '' let path = ''
// 文件id // 文件id
let fileIds = '' let fileIds = ''
if(!uploadFiles || uploadFiles.length==0){ if (!uploadFiles || uploadFiles.length === 0) {
path = '' path = ''
} }
let arr = [] let arr = []
// 如果returnid为true 只返回id // 如果returnid为true 只返回id
if(this.returnId){ if (this.returnId) {
for(var a=0;a<uploadFiles.length;a++){ for (let a = 0; a < uploadFiles.length; a++) {
if(uploadFiles[a].status === 'done' ) { if (uploadFiles[a].status === 'done') {
arr.push(uploadFiles[a].response.result.id) arr.push(uploadFiles[a].response.result.id)
}else{ } else {
return
}
}
if(arr.length>0){
fileIds = arr.join(',')
}
this.$emit('change', fileIds)
return
}
for(var a=0;a<uploadFiles.length;a++){
if(uploadFiles[a].status === 'done' ) {
arr.push(uploadFiles[a].url)
}else{
return return
} }
} }
if(arr.length>0){ if (arr.length > 0) {
path = arr.join(',') fileIds = arr.join(',')
} }
this.$emit('change', path) this.$emit('change', fileIds)
}, return
beforeUpload(file){ }
this.uploadGoOn=true
var fileType = file.type for (let a = 0; a < uploadFiles.length; a++) {
if(this.fileType===FILE_TYPE_IMG){ if (uploadFiles[a].status === 'done') {
if(fileType.indexOf('image')<0){ arr.push(uploadFiles[a].url)
this.$message.warning('请上传图片') } else {
this.uploadGoOn=false return
return false
}
} }
//TODO 扩展功能验证文件大小 }
return true if (arr.length > 0) {
}, path = arr.join(',')
handleChange(info) { }
if(!info.file.status && this.uploadGoOn === false){ this.$emit('change', path)
info.fileList.pop() },
beforeUpload(file) {
this.uploadGoOn = true
let fileType = file.type
if (this.fileType === FILE_TYPE_IMG) {
if (fileType.indexOf('image') < 0) {
this.$message.warning('请上传图片')
this.uploadGoOn = false
return false
} }
let fileList = info.fileList }
if(info.file.status==='done'){ //TODO 扩展功能验证文件大小
if(this.number>0){ return true
fileList = fileList.slice(-this.number) },
} handleChange(info) {
if(info.file.response.success){ if (!info.file.status && this.uploadGoOn === false) {
fileList = fileList.map((file) => { info.fileList.pop()
if (file.response) { }
// let reUrl = `${file.response.result.id}?token=${Vue.ls.get(ACCESS_TOKEN)}&fullfilename=${file.response.result.fileName}`; let fileList = info.fileList
file.url = getFileAccessHttpUrl(file.response.result.id) if (info.file.status === 'done') {
} if (this.number > 0) {
return file fileList = fileList.slice(-this.number)
})
}
//this.$message.success(`${info.file.name} 上传成功!`);
}else if (info.file.status === 'error') {
this.$message.error(`${info.file.name} 上传失败.`)
}else if(info.file.status === 'removed'){
this.handleDelete(info.file)
} }
this.fileList = fileList if (info.file.response.success) {
if(info.file.status==='done' || info.file.status === 'removed'){ fileList = fileList.map((file) => {
//returnUrl为true时仅返回文件路径 if (file.response) {
if(this.returnUrl){ // let reUrl = `${file.response.result.id}?token=${Vue.ls.get(ACCESS_TOKEN)}&fullfilename=${file.response.result.fileName}`;
this.handlePathChange() file.url = getFileAccessHttpUrl(file.response.result.id)
}else{
//returnUrl为false时返回文件名称、文件路径及文件大小
this.newFileList = []
for(var a=0;a<fileList.length;a++){
// update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错
if(fileList[a].status === 'done' ) {
var fileJson = {
fileName:fileList[a].name,
filePath:fileList[a].url,
fileSize:fileList[a].size
}
this.newFileList.push(fileJson)
}else{
return
}
// update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错
} }
this.$emit('change', this.newFileList) return file
}
}
},
handleDelete(file){
//如有需要新增 删除逻辑
console.log(file)
},
handlePreview(file) {
if (file && file.url) {
var fileFullUrl = `${window._CONFIG['domianWebSocketURL']}/sys/common/download/${file.response.result.id}?token=${Vue.ls.get(ACCESS_TOKEN)}&fullfilename=${file.name}`
// let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(Base64.encode(fileFullUrl))}`
let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileFullUrl)}`
window.open(url)
}
},
getFileUrl(fileId){
return `${window._CONFIG['domianURL']}/sys/common/download/${fileId}`
},
/**
* 通过文件的id获取文件的相关信息
* @param id
*/
getFileInfo(id) {
return new Promise(resolve => {
let result = {}
getFileInfo({id: id}).then(res => {
if (res.success) {
result = res.result
}
}).finally(() => {
resolve(result)
}) })
}) }
//this.$message.success(`${info.file.name} 上传成功!`);
} else if (info.file.status === 'error') {
this.$message.error(`${info.file.name} 上传失败.`)
} else if (info.file.status === 'removed') {
this.handleDelete(info.file)
}
this.fileList = fileList
if (info.file.status === 'done' || info.file.status === 'removed') {
//returnUrl为true时仅返回文件路径
if (this.returnUrl) {
this.handlePathChange()
} else {
//returnUrl为false时返回文件名称、文件路径及文件大小
this.newFileList = []
for (let a = 0; a < fileList.length; a++) {
// update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错
if (fileList[a].status === 'done') {
let fileJson = {
fileName: fileList[a].name,
filePath: fileList[a].url,
fileSize: fileList[a].size
}
this.newFileList.push(fileJson)
} else {
return
}
// update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错
}
this.$emit('change', this.newFileList)
}
} }
}, },
mounted(){}, handleDelete(file) {
model: { //如有需要新增 删除逻辑
prop: 'value', console.log(file)
event: 'change' },
handlePreview(file) {
if (file && file.url) {
const fileFullUrl = `${window._CONFIG['domianWebSocketURL']}/sys/common/download/${file.response.result.id}?token=${Vue.ls.get(ACCESS_TOKEN)}&fullfilename=${file.name}`
let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(Base64.encode(fileFullUrl))}`
// let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileFullUrl)}`
window.open(url)
}
},
getFileUrl(fileId) {
return `${window._CONFIG['domianURL']}/sys/common/download/${fileId}`
},
/**
* 通过文件的id获取文件的相关信息
* @param id
*/
getFileInfo(id) {
return new Promise(resolve => {
let result = {}
getFileInfo({id: id}).then(res => {
if (res.success) {
result = res.result
}
}).finally(() => {
resolve(result)
})
})
} }
},
mounted() {
},
model: {
prop: 'value',
event: 'change'
} }
}
</script> </script>
<style lang="less"> <style lang="less">
.uploadty-disabled{ .uploadty-disabled {
.ant-upload-list-item { .ant-upload-list-item {
.anticon-close{ .anticon-close {
display: none; display: none;
} }
.anticon-delete{
display: none; .anticon-delete {
} display: none;
} }
} }
}
</style> </style>
+2 -2
View File
@@ -76,7 +76,7 @@ module.exports = {
}, },
devServer: { devServer: {
port: 3000, port: 21825,
proxy: { proxy: {
/* '/api': { /* '/api': {
target: 'https://mock.ihx.me/mock/5baf3052f7da7e07e04a5116/antd-pro', //mock API接口系统 target: 'https://mock.ihx.me/mock/5baf3052f7da7e07e04a5116/antd-pro', //mock API接口系统
@@ -88,7 +88,7 @@ module.exports = {
},*/ },*/
'/jero-boot': { '/jero-boot': {
// '' // ''
target: 'http://localhost:8080', //请求本地 jero-boot后台项目 target: 'http://localhost:21824', //请求本地 jero-boot后台项目
ws: false, ws: false,
changeOrigin: true, changeOrigin: true,
}, },