[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
+100 -89
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,27 +31,28 @@
<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)
}
export default {
name: 'JUpload', name: 'JUpload',
data(){ data() {
return { return {
uploadAction:window._CONFIG['domianURL']+'/sys/common/upload', uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
headers:{}, headers: {},
fileList: [], fileList: [],
newFileList: [], newFileList: [],
uploadGoOn:true, uploadGoOn: true,
} }
}, },
props: { props: {
@@ -102,9 +104,9 @@
* true 仅返回文件id * true 仅返回文件id
* false 返回reurl * false 返回reurl
* */ * */
returnId:{ returnId: {
type:Boolean, type: Boolean,
required:false, required: false,
default: false default: false
}, },
number: { number: {
@@ -118,15 +120,15 @@
default: true default: true
}, },
}, },
watch:{ watch: {
value:{ value: {
immediate: true, immediate: true,
handler() { handler() {
let val = this.value let val = this.value
if (val instanceof Array) { if (val instanceof Array) {
if(this.returnUrl){ if (this.returnUrl) {
this.initFileList(val.join(',')) this.initFileList(val.join(','))
}else{ } else {
this.initFileListArr(val) this.initFileListArr(val)
} }
} else { } else {
@@ -135,53 +137,53 @@
} }
} }
}, },
computed:{ computed: {
//透传给下级组件的事件,需要排除本组件使用的change事件 //透传给下级组件的事件,需要排除本组件使用的change事件
childListeners() { childListeners() {
const vm = this // const vm = this
let result = Object.assign({}, let result = Object.assign({},
this.$listeners, this.$listeners,
) )
delete result.change delete result.change
return result return result
}, },
isImageComp(){ isImageComp() {
return this.fileType === FILE_TYPE_IMG return this.fileType === FILE_TYPE_IMG
}, },
complistType(){ complistType() {
return this.fileType === FILE_TYPE_IMG?'picture-card':'text' return this.fileType === FILE_TYPE_IMG ? 'picture-card' : 'text'
}, },
}, },
created(){ created() {
const token = Vue.ls.get(ACCESS_TOKEN) const token = Vue.ls.get(ACCESS_TOKEN)
//---------------------------- begin 图片左右换位置 ------------------------------------- //---------------------------- begin 图片左右换位置 -------------------------------------
this.headers = {'X-Access-Token':token} this.headers = {'X-Access-Token': token}
this.containerId = 'container-ty-'+new Date().getTime() this.containerId = 'container-ty-' + new Date().getTime()
//---------------------------- end 图片左右换位置 ------------------------------------- //---------------------------- end 图片左右换位置 -------------------------------------
}, },
methods:{ methods: {
initFileListArr(val){ initFileListArr(val) {
if(!val || val.length==0){ if (!val || val.length === 0) {
this.fileList = [] this.fileList = []
return return
} }
for(var a=0;a<val.length;a++){ for (let a = 0; a < val.length; a++) {
this.fileList.forEach((item)=>{ this.fileList.forEach((item) => {
if (item.url === val[a]){ if (item.url === val[a]) {
item.uid = uidGenerator() item.uid = uidGenerator()
item.response.status = 'done' item.response.status = 'done'
} }
}) })
} }
}, },
async initFileList(paths){ async initFileList(paths) {
if(!paths || paths.length === 0){ if (!paths || paths.length === 0) {
this.fileList = [] this.fileList = []
return return
} }
let arr = paths.split(',') let arr = paths.split(',')
// 返回路径的时候,对路径进行操作,取出所属id // 返回路径的时候,对路径进行操作,取出所属id
if(!this.returnId && arr.length > 0) { if (!this.returnId && arr.length > 0) {
const newArr = [] const newArr = []
arr.map(item => { arr.map(item => {
let itemArr = item.split('/') let itemArr = item.split('/')
@@ -192,66 +194,73 @@
const fileList = [] const fileList = []
for (let a = 0; a < arr.length; a++) { for (let a = 0; a < arr.length; a++) {
// 获取每一个文件的信息,组成fileList // 获取每一个文件的信息,组成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 return
} }
} }
if(arr.length>0){ if (arr.length > 0) {
fileIds = arr.join(',') fileIds = arr.join(',')
} }
this.$emit('change', fileIds) this.$emit('change', fileIds)
return return
} }
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].url) arr.push(uploadFiles[a].url)
}else{ } else {
return return
} }
} }
if(arr.length>0){ if (arr.length > 0) {
path = arr.join(',') path = arr.join(',')
} }
this.$emit('change', path) this.$emit('change', path)
}, },
beforeUpload(file){ beforeUpload(file) {
this.uploadGoOn=true this.uploadGoOn = true
var fileType = file.type let fileType = file.type
if(this.fileType===FILE_TYPE_IMG){ if (this.fileType === FILE_TYPE_IMG) {
if(fileType.indexOf('image')<0){ if (fileType.indexOf('image') < 0) {
this.$message.warning('请上传图片') this.$message.warning('请上传图片')
this.uploadGoOn=false this.uploadGoOn = false
return false return false
} }
} }
@@ -259,15 +268,15 @@
return true return true
}, },
handleChange(info) { handleChange(info) {
if(!info.file.status && this.uploadGoOn === false){ if (!info.file.status && this.uploadGoOn === false) {
info.fileList.pop() info.fileList.pop()
} }
let fileList = info.fileList let fileList = info.fileList
if(info.file.status==='done'){ if (info.file.status === 'done') {
if(this.number>0){ if (this.number > 0) {
fileList = fileList.slice(-this.number) fileList = fileList.slice(-this.number)
} }
if(info.file.response.success){ if (info.file.response.success) {
fileList = fileList.map((file) => { fileList = fileList.map((file) => {
if (file.response) { if (file.response) {
// let reUrl = `${file.response.result.id}?token=${Vue.ls.get(ACCESS_TOKEN)}&fullfilename=${file.response.result.fileName}`; // let reUrl = `${file.response.result.id}?token=${Vue.ls.get(ACCESS_TOKEN)}&fullfilename=${file.response.result.fileName}`;
@@ -277,29 +286,29 @@
}) })
} }
//this.$message.success(`${info.file.name} 上传成功!`); //this.$message.success(`${info.file.name} 上传成功!`);
}else if (info.file.status === 'error') { } else if (info.file.status === 'error') {
this.$message.error(`${info.file.name} 上传失败.`) this.$message.error(`${info.file.name} 上传失败.`)
}else if(info.file.status === 'removed'){ } else if (info.file.status === 'removed') {
this.handleDelete(info.file) this.handleDelete(info.file)
} }
this.fileList = fileList this.fileList = fileList
if(info.file.status==='done' || info.file.status === 'removed'){ if (info.file.status === 'done' || info.file.status === 'removed') {
//returnUrl为true时仅返回文件路径 //returnUrl为true时仅返回文件路径
if(this.returnUrl){ if (this.returnUrl) {
this.handlePathChange() this.handlePathChange()
}else{ } else {
//returnUrl为false时返回文件名称、文件路径及文件大小 //returnUrl为false时返回文件名称、文件路径及文件大小
this.newFileList = [] this.newFileList = []
for(var a=0;a<fileList.length;a++){ for (let a = 0; a < fileList.length; a++) {
// update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错 // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错
if(fileList[a].status === 'done' ) { if (fileList[a].status === 'done') {
var fileJson = { let fileJson = {
fileName:fileList[a].name, fileName: fileList[a].name,
filePath:fileList[a].url, filePath: fileList[a].url,
fileSize:fileList[a].size fileSize: fileList[a].size
} }
this.newFileList.push(fileJson) this.newFileList.push(fileJson)
}else{ } else {
return return
} }
// update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错 // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时,控制台报错
@@ -308,19 +317,19 @@
} }
} }
}, },
handleDelete(file){ handleDelete(file) {
//如有需要新增 删除逻辑 //如有需要新增 删除逻辑
console.log(file) console.log(file)
}, },
handlePreview(file) { handlePreview(file) {
if (file && file.url) { 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}` 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(Base64.encode(fileFullUrl))}`
let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileFullUrl)}` // let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileFullUrl)}`
window.open(url) window.open(url)
} }
}, },
getFileUrl(fileId){ getFileUrl(fileId) {
return `${window._CONFIG['domianURL']}/sys/common/download/${fileId}` return `${window._CONFIG['domianURL']}/sys/common/download/${fileId}`
}, },
/** /**
@@ -340,23 +349,25 @@
}) })
} }
}, },
mounted(){}, mounted() {
},
model: { model: {
prop: 'value', prop: 'value',
event: 'change' 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{
.anticon-delete {
display: none; 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,
}, },