文件上传+下载+预览+删除
这个是在vue中封装的组件,需求就是单个上传文件,最后把返回的文件信息传到表单的files数组中就行,时间比较仓促,如果有不好的我改
// 封装的组件:目录是components/地址/文件名.vue
<template>
<div class="upload-file">
<el-upload
multiple
// 上传文件的名称,我们后台要这个名
name="multipartFile"
// 点击文件上传直接就传到后端提供的地址了
:action="uploadFileUrl"
// 这个是我们文件需要传递的动态的编码,可以不需要
:data="{systemCode: '001'}"
:limit="limit"
// 文件列表
:file-list="fileList"
:before-upload="handleBeforeUpload"
:on-exceed="handleExceed"
:on-error="handleUploadError"
:on-success="handleUploadSuccess"
:show-file-list="false"
:headers="headers"
class="upload-file-uploader"
ref="fileUpload">
<!-- 上传按钮 -->
<el-button size="mini" type="primary" plain v-if="!disabled">选取文件</el-button>
<!-- 上传提示 -->
<div class="el-upload__tip" slot="tip" v-if="showTip && !disabled">
请上传
<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
的文件
</div>
</el-upload>
<!-- 文件列表 -->
<transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul" style="min-width: 300px;">
<li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList" :key="file.fileId">
<el-link :href="`${baseUrl}${file.filePath}`" :underline="false" target="_blank">
<span class="el-icon-document" style="padidng-left: 10px;"> {{ getFileName(file.fileName) }} </span>
</el-link>
<div class="ele-upload-list__item-content-action" style="width: 50px; text-align: center;">
<el-link :underline="false" @click="handleDelete(index)" type="danger" v-if="!disabled">删除</el-link>
</div>
<div class="ele-upload-list__item-content-action" style="width: 50px; text-align: center;">
<el-link :underline="false" @click="handlePreview(file)" type="danger" v-if="disabled">预览</el-link>
</div>
<div class="ele-upload-list__item-content-action" style="width: 50px; text-align: center;">
<el-link :underline="false" @click="handleDownload(file)" type="danger">下载</el-link>
</div>
</li>
</transition-group>
<el-dialog class="my-dialog" title="文件预览" :visible.sync="preview.open" append-to-body>
<vue-office-docx v-if="fileSuffix == 'docx'" :src="preview.url" style="height: 100vh;"/>
<vue-office-excel v-else-if="fileSuffix == 'xlsx'" :src="preview.url" style="height: 100vh;" />
<vue-office-pdf v-else-if="fileSuffix == 'pdf'" :src="preview.url" style="height: 100vh;" />
<div style="text-align:center;" v-else>暂不支持该文件预览,请下载预览</div>
<!-- <div slot="footer" class="dialog-footer">
<el-button class="cancel" @click="previewCancel">取 消</el-button>
</div> -->
</el-dialog>
</div>
</template>
<script>
//引入VueOfficeDocx组件 这几个组件都是需要安装的 npm install 安装
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
//引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
//引入VueOfficePdf组件
import VueOfficePdf from '@vue-office/pdf'
export default {
name: "FileUploadReset",
props: {
// 数量限制
limit: {
type: Number,
default: 5,
},
// 大小限制(MB)
fileSize: {
type: Number,
default: 5,
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
fileType: {
type: Array,
default: () => ["doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf"],
},
// 是否显示提示
isShowTip: {
type: Boolean,
default: true
},
// 在外部使用文件编辑的dialog弹框回显需要把文件传进来
formFileList: {
type: Array,
default: () => ([])
},
// 这个是后台表格数据查看详情的时候不能显示一些信息,比如文件大小提示
disabled: {
type: Boolean,
default: false
}
},
components: {
VueOfficeDocx,
VueOfficeExcel,
VueOfficePdf
},
data() {
return {
number: 0,
uploadList: [],
baseUrl: process.env.VUE_APP_BASE_API+ "/地址/地址/地址?fileName=",
uploadFileUrl: process.env.VUE_APP_BASE_API + "/地址/地址/地址", // 上传文件服务器地址
headers: {
Authorization: "Bearer " + getToken() // 我们上传文件需要有一些headers的信息
},
fileList: [],
lookFile: false,
url: "",
// 文件预览
preview: {
open: false,
url: ""
},
fileSuffix: ""
};
},
watch: {
formFileList: {
handler(val) {
if (val !== undefined) {
this.fileList = val
}
if (val == null) {
this.fileList = []
return
}
},
deep: true,
immediate: true
},
},
computed: {
// 是否显示提示
showTip() {
return this.isShowTip && (this.fileType || this.fileSize);
},
},
methods: {
// 上传前校检格式和大小
handleBeforeUpload(file) {
// 校检文件类型
if (this.fileType) {
const fileName = file.name.split('.');
const fileExt = fileName[fileName.length - 1];
const isTypeOk = this.fileType.length? this.fileType.indexOf(fileExt) >= 0: [];
if (!isTypeOk) {
this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
return false;
}
}
// 校检文件大小
if (this.fileSize) {
const isLt = file.size / 1024 / 1024 < this.fileSize;
if (!isLt) {
this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
return false;
}
}
this.$modal.loading("正在上传文件,请稍候...");
this.number++;
return true;
},
// 文件个数超出
handleExceed() {
this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
},
// 上传失败
handleUploadError(err) {
this.$modal.msgError("上传文件失败,请重试");
this.$modal.closeLoading()
},
// 上传成功回调
handleUploadSuccess(res, file) {
if (res.code === 200) {
this.uploadList.push(res.data);
this.uploadedSuccessfully();
} else {
this.number--;
this.$modal.closeLoading();
this.$modal.msgError(res.msg);
this.$refs.fileUpload.handleRemove(file);
this.uploadedSuccessfully();
}
},
// 删除文件,普通删除,没有调用接口,应为还没上传
handleDelete(index) {
this.fileList.splice(index, 1);
this.$emit("input", this.listToString(this.fileList));
},
// 上传结束处理
uploadedSuccessfully() {
if (this.number > 0 && this.uploadList.length === this.number) {
this.fileList = this.fileList.concat(this.uploadList);
this.uploadList = [];
this.number = 0;
this.$emit("input", this.listToString(this.fileList));
this.$modal.closeLoading();
this.$emit("fileUploadSuccess", this.fileList)
}
},
// 获取文件名称
getFileName(name) {
if (name?.lastIndexOf("/") > -1) {
return name.slice(name.lastIndexOf("/") + 1);
} else {
return name;
}
},
// 对象转成指定字符串分隔
listToString(list, separator) {
let strs = "";
separator = separator || ",";
for (let i in list) {
strs += list[i].url + separator;
}
return strs != '' ? strs.substr(0, strs.length - 1) : '';
},
resetFileList() {
this.fileList = []
},
// 下载是调用自己后台的接口的,downloadFile就是在api文件封装的url
handleDownload(file) {
下载方法(file.fileId).then(res => {
this.exportFunction(res, file.fileName, file.fileType)
})
},
exportFunction(response, name, type) {
// const downloadType = type === "pdf" ? 'application/pdf': 'application/msword'
const link = document.createElement('a')
// vnd.ms-excel vnd.ms-csv
const blob = new Blob([response], { type })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', name, type)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
},
// 预览
handlePreview(file) {
this.preview.url = ""
this.fileSuffix = file.suffix
预览方法(file.fileId).then(res => {
this.preview.url = "我们后端返回的地址需要拼接" + res
this.preview.open = true
})
},
previewCancel() {
this.preview.open = false
this.preview.url = ""
},
}
};
</script>
<style scoped lang="scss">
.upload-file-uploader {
margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
border: 1px solid #e4e7ed;
line-height: 2;
margin-bottom: 10px;
position: relative;
}
.upload-file-list .ele-upload-list__item-content {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
.ele-upload-list__item-content-action .el-link {
margin-right: 10px;
}
</style>
使用组件
<file-upload-reset ref="fileResetRef" @fileUploadSuccess="fileUploadSuccessHandle" :formFileList="form.files" :disabled="isReadonly"></file-upload-reset>
// 在methods中添加文件上传成功的回调,返回的是一个数组,直接放到表单里就好了
fileUploadSuccessHandle(fileList) {
this.form.files = fileList
},
// 表单重置把这个文件列表也赋值为空就好了
reset() {
this.form = {
...省略好多的字段
files: [],
};
this.resetForm("form");
}
// 表单回显后台返回就好了,在组件上formFileList="form.files" 传递回去就回显了