发布时间:2025-01-11 10:01
支持的文件类型,这里我限制了14种,如下:
this.attachmentType = strRebuild([
"txt",
"xls",
"xlsx",
"doc",
"docx",
"ppt",
"pptx",
"visio",
"pdf",
"jpg",
"png",
"jpeg",
"rar",
"zip"
])
页面上需要一个上传文件的输入框,这里我使用input,type设置为file;
<template>
<div>
<input
type="file"
ref="file"
multiple="multiple"
@change="handleFileChange"
/>
<el-button @click="oninput" size="mini" :class="style">添加附件</el-button>
<div slot="tip" class="el-upload__tip">支持上传 {{ attachmentType }}</div>
</div>
</template>
当点击按钮【添加附件】时,用$ref触发input事件;
handleFileChange(e) {
//验证上传文件的类型
if(this.attachmentType.indexOf(lastSubstring(e.target.files[0].name,'.').toLowerCase()) !== -1) {
this.attachmentList.push(e.target.files[0]);
} else {
this.$message.error("不支持上传该类型的附件")
}
},
oninput() {
this.$refs["file"].click();
}
数据提交至后端,使用FormData的方式,还需特别注意的是:请求的后端接口要设置"Content-Type"为 “multipart/form-data”。
//上传文件
uploadAttachment(attachment) { //接受的参数attachment是File类型
let params = {
tableName: "ATTACHMENT",
column: "FILE_CONTENT",
data: new FormData()
};
params.data.append("_files", attachment);
params.data.append("FILE_NAME", attachment.name);
params.data.append("FILE_SIZE", attachment.size);
params.data.append("MAIL_ID", uuidv4());
uploadBlobData(params).then(res => { //uploadBlobData为我的后端请求
if(res.data.status == 200) {
this.$message.success("上传附件成功")
}
});
},
字符串相关工具类方法:
// 数组根据指定分隔符重组为字符串
export const strRebuild = (arr, split) => {
if (
arr === undefined ||
arr === null ||
!(arr instanceof Array) ||
arr.length === 0
) {
return "";
}
if (split === undefined || split === null) {
split = ",";
}
var str = "";
arr.forEach((v, i) => {
if (i === arr.length - 1) {
str = str + v;
} else {
str = str + v + split;
}
});
return str;
};
// 截取最后一个指定字符后面的字符串
export const lastSubstring = (str, split) => {
if (
str === undefined ||
str === null ||
split === undefined ||
split === null
) {
return "";
}
return str.substring(str.lastIndexOf(split) + 1);
};
export default {
strRebuild,
lastSubstring
};
思路:
请求后端获取文件数据,因为上传附件时通过向后端发送POST请求将文件以Blob形式存在了数据库表中,所以向后端发送GET请求获取文件数据;
queryAttachment(mailId) {
let params = {
tableName: "ATTACHMENT",
page: 1,
sort: "TIME",
where: "MAIL_ID,eq,'" + mailId + "'"
};
queryData(params).then(res => { //queryData为我的后端请求
this.attachmentList = res.data.data; //附件列表
});
}
页面上每个文件后需要一个下载的按钮
<el-row
v-for="file in attachmentList"
:key="file.ID"
>
<el-col :span="18">{{file.FILE_NAME}}</el-col>
<el-col :span="6">
<el-button plain size="mini" @click="downloadFile(file)">下载</el-button>
</el-col>
</el-row>
下载文件,将Base64形式的二进制文件转换为Blob类型,注意要根据文件类型设置下载Blob时的类型;
downloadFile(file) {
let fileType = lastSubstring(file.FILE_NAME, ".");
let blob = bs64toBlob(
file.FILE_CONTENT,
this.downloadBlobContentType[fileType.toLowerCase()]
); //file.FILE_CONTENT为Base64形式的二进制数据
if ("download" in document.createElement("a")) {
let elink = document.createElement("a");
elink.download = file.FILE_NAME;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
} else {
navigator.msSaveBlob(blob, file.FILE_NAME);
}
},
根据文件类型设置下载Blob时对应的type类型,如果需要更多类型,扩展该对象数据即可;
//下载blob二进制文件时对应的type类型
downloadBlobContentType: {
txt: "text/plain",
xls: "application/vnd.ms-excel",
xlsx:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
doc: "application/msword",
docx:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
ppt: "application/vnd.ms-powerpoint",
pptx:
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
visio: "application/vnd.visio",
pdf: "application/pdf",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
zip: "application/zip",
rar: "application/x-rar-compressed"
}
base64 转换为 Blob的方法,新建文件base64toBlob.js
。
// base64 转换为 Blob
export const bs64toBlob = (bs64Data, contentType, sliceSize) => {
contentType = contentType || "";
sliceSize = sliceSize || 512;
var byteCharacters = window.atob(bs64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
};
export default {
bs64toBlob
};