文件上传备份

This commit is contained in:
XaoLi717 2024-09-23 16:41:03 +08:00
parent af3e24ec48
commit db7d055392

View File

@ -0,0 +1,383 @@
<template>
<div class="upload-file">
<el-upload
ref="uploadRef"
v-model:file-list="fileList"
:action="uploadUrl"
:auto-upload="autoUpload"
:before-upload="beforeUpload"
:disabled="disabled"
:drag="drag"
:http-request="httpRequest"
:limit="props.limit"
:multiple="props.limit > 1"
:on-error="excelUploadError"
:on-exceed="handleExceed"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleFileSuccess"
:show-file-list="true"
class="upload-file-uploader"
name="file"
>
<el-button v-if="!disabled" type="primary">
<Icon icon="ep:upload-filled" />
选取文件
</el-button>
<template v-if="isShowTip && !disabled" #tip>
<div style="font-size: 8px">
大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
</div>
<div style="font-size: 8px">
格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b> 的文件
</div>
</template>
<template #file="row">
<div class="flex items-center">
<span>{{ row.file.name }}</span>
<div class="ml-10px" >
<el-link
:underline="false"
@click="handleView(row.file)"
target="_blank"
type="primary"
>预览
</el-link>
<!-- <i-frame :src="'https://view.officeapps.live.com/op/view.aspx?src='+encodeURIComponent(row.file.url)"/>-->
</div>
<div class="ml-10px" >
<el-link
:underline="false"
@click="edit(row)"
target="_blank"
type="primary"
>编辑
</el-link>
</div>
<div class="ml-10px">
<el-link
:underline="false"
target="_blank"
@click="downloadFile(row.file)"
type="primary"
>原文件下载
</el-link>
</div>
<div class="ml-10px" >
<el-link
:underline="false"
@click="download(row)"
target="_blank"
type="primary"
>编辑后下载
</el-link>
</div>
<div class="ml-10px">
<el-button link type="danger" @click="handleRemove(row.file)"> 删除</el-button>
</div>
</div>
</template>
</el-upload>
</div>
</template>
<script lang="ts" setup>
import { propTypes } from '@/utils/propTypes'
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { isString } from '@/utils/is'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { UploadFile } from 'element-plus/es/components/upload/src/upload'
import {getAccessToken} from "@/utils/auth";
import axios from "axios";
import {onlyofApi} from "@/api/only/only";
defineOptions({ name: 'UploadFile' })
const message = useMessage() //
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
modelValue: propTypes.oneOfType<string | string[]>([String, Array<String>]).isRequired,
fileType: propTypes.array.def(['doc', 'xls', 'ppt', 'txt', 'pdf']), // , ['png', 'jpg', 'jpeg']
fileSize: propTypes.number.def(5), // (MB)
limit: propTypes.number.def(5), //
autoUpload: propTypes.bool.def(true), //
drag: propTypes.bool.def(true), //
isShowTip: propTypes.bool.def(true), //
disabled: propTypes.bool.def(false) // ==> false
})
// ========== ==========
const uploadRef = ref<UploadInstance>()
const uploadList = ref<UploadUserFile[]>([])
const fileList = ref<UploadUserFile[]>([])
const MysqlUrl = ref<UploadUserFile[]>([])
const uploadNumber = ref<number>(0)
const { uploadUrl, httpRequest } = useUpload()
const queryParamsOnly = reactive({
pageNo: 1,
pageSize: 10,
fileName: undefined,
fileSize: undefined,
fileType: undefined,
filePath: undefined,
uploadDate: [],
status: undefined,
createTime: [],
})
/** 查询列表 */
const GotoFile = ref(false)
const getList = async () => {
const data = await onlyofApi.getonlyofPage(queryParamsOnly)
GotoFile.value=false
if (data.total<=0){
message.error('未找到文件重新上传')
GotoFile.value=false
}else {
message.success('正在打开')
GotoFile.value=true
}
}
//
const edit = async (row) => {
console.log(row)
let name = row.file.name.trim()
queryParamsOnly.pageNo = 1
queryParamsOnly.fileName=name
await getList()
if (!GotoFile.value){
return;
}
console.log(name)
const token = getAccessToken();
window.open(`http://192.168.1.3:48080/admin-api/only/onlyof/edit?name=${name}&userName=admin&userId=1&token=${token}`);
};
//
const download = async (row) => {
let name = row.file.name.trim()
try {
const token = getAccessToken();
const response = await axios.get(`http://192.168.1.3:48080/admin-api/only/onlyof/editStatus?name=${name}&token=${token}`);
if (response.data.error === 0) {
alert('文档正在编辑5秒后开始下载最新版');
setTimeout(() => {
window.location.href = `http://192.168.1.3:48080/admin-api/only/onlyof/download?name=v1${name}&token=${token}`;
}, 5000);
} else {
window.location.href = `http://192.168.1.3:48080/admin-api/only/onlyof/download?name=${name}&token=${token}`;
}
} catch (error) {
console.error('Download failed:', error);
}
};
//
const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
if (fileList.value.length >= props.limit) {
message.error(`上传文件数量不能超过${props.limit}个!`)
return false
}
let fileExtension = ''
if (file.name.lastIndexOf('.') > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
}
const isImg = props.fileType.some((type: string) => {
if (file.type.indexOf(type) > -1) return true
return !!(fileExtension && fileExtension.indexOf(type) > -1)
})
const isLimit = file.size < props.fileSize * 1024 * 1024
if (!isImg) {
message.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`)
return false
}
if (!isLimit) {
message.error(`上传文件大小不能超过${props.fileSize}MB!`)
return false
}
message.success('正在上传文件,请稍候...')
uploadNumber.value++
}
//
// const handleFileChange = (uploadFile: UploadFile): void => {
// uploadRef.value.data.path = uploadFile.name
// }
//
const handleFileSuccess: UploadProps['onSuccess'] = (res: any): void => {
message.success('上传成功')
//
const index = fileList.value.findIndex((item) => item.response?.data === res.data)
fileList.value.splice(index, 1)
console.log("res",res)
/**
* 拼接更加明显的特殊字符串来便于切割
* */
uploadList.value.push({ name: (res.data[0]+"&&$#$"+res.data[1])+" ", url: (res.data[0]+"&&$#$"+res.data[1])+" "})
if (uploadList.value.length == uploadNumber.value) {
fileList.value.push(...uploadList.value)
MysqlUrl.value.push(...uploadList.value)
// console.log("fileList.value",fileList.value)
// console.log("MysqlUrl.value",MysqlUrl.value)
uploadList.value = []
uploadNumber.value = 0
emitUpdateModelValue()
}
}
//
const handleExceed: UploadProps['onExceed'] = (): void => {
message.error(`上传文件数量不能超过${props.limit}个!`)
}
//
const excelUploadError: UploadProps['onError'] = (): void => {
message.error('导入数据失败,请您重新上传!')
}
//
const handleRemove = (file: UploadFile) => {
const index = fileList.value.map((f) => f.name).indexOf(file.name)
if (index > -1) {
//
fileList.value.splice(index, 1)
MysqlUrl.value.splice(index,1)
// console.log("fileList",fileList.value)
// console.log("MysqlUrl",MysqlUrl.value)
emitUpdateModelValue2()
}
}
//
const handleView = (file)=> {
const url = file.url
if (!url) {
console.error("文件不可预览");
}
const file2 = url.substring(url.length-5,url.length).trim().toLowerCase()
console.log(file2)
if (file2==="docx"||file2==="xlsx"||file2==="pptx"){
window.open("https://view.officeapps.live.com/op/view.aspx?src="+encodeURIComponent(url),'_blank')
}else if(file2===".txt"||file2===".pdf"){
window.open(url, '_blank');
}
}
//
const downloadFile = async (file)=> {
console.log("file",file)
//使 fetch API Blob
const response = await fetch(file.url);
// response blob
const blob = await response.blob();
// <a>
const link = document.createElement('a')
// URL Blob
link.href = URL.createObjectURL(blob);
//使
link.download = file.name
//link
document.body.appendChild(link);
//
link.click();
//link
document.body.removeChild(link);
// URL
URL.revokeObjectURL(link.href);
}
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
console.log(uploadFile)
}
//
watch(
() => props.modelValue,
(val: string | string[]) => {
// console.log("val",val)
if (!val) {
fileList.value = [] // fix
return
}
fileList.value = [] //
// 1
if (isString(val)) {
fileList.value.push(
...val.split(',').map((url) => ({ name: url.substring(url.lastIndexOf('/') + 1), url }))
)
return
}
// 2
fileList.value.push(
...(val as string[]).map((url) => ({ name: url.substring(0,url.indexOf("&&$#")),url:url.substring(url.indexOf("&&$#")+5,url.length) }))
)
//val
if (val[0]==""){
fileList.value = []
}
//val val MysqlUrlMysqlUrl push val
if (val[0]!==""&&val.length>0&&MysqlUrl.value.length==0){
MysqlUrl.value.push(
...(val as string[]).map((url) => ({ name: url,url: url}))
);
}
// console.log("11111fileList", fileList.value)
// console.log("11111MysqlUrl", MysqlUrl.value)
},
{ immediate: true, deep: true }
)
//
const emitUpdateModelValue = () => {
// 1
let result: string | string[] = MysqlUrl.value.map((file) => file.url!)
// 2
if (props.limit === 1 || isString(props.modelValue)) {
result = result.join(',')
}
// console.log("result",result)
emit('update:modelValue', result)
}
//
const emitUpdateModelValue2 = () => {
// 1
let result: string | string[] = MysqlUrl.value.map((file) => file.url!)
// 2
if (props.limit === 1 || isString(props.modelValue)) {
result = result.join(',')
}
// console.log("result",result)
emit('update:modelValue', result)
// 便
MysqlUrl.value = []
}
</script>
<style lang="scss" scoped>
.upload-file-uploader {
margin-bottom: 5px;
}
:deep(.upload-file-list .el-upload-list__item) {
position: relative;
margin-bottom: 10px;
line-height: 2;
border: 1px solid #e4e7ed;
}
:deep(.el-upload-list__item-file-name) {
max-width: 250px;
}
:deep(.upload-file-list .ele-upload-list__item-content) {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
:deep(.ele-upload-list__item-content-action .el-link) {
margin-right: 10px;
}
</style>