前端重写组件代码:
<template>
<!-- 单附件上传,domin域,businessId所属的id,域一般为模块使用的标识,默认传输word转为pdf -->
<div>
<el-upload
v-loading="loading"
:action="url"
:show-file-list="false"
:on-success="success"
:data="{ domain: domain, businessId: businessId }"
multiple
:limit="1"
:on-error="error"
:headers="headers"
:before-upload="fileBeforeUpload"
:on-progress="progress"
:accept="accept"
ref="upload"
>
<el-button slot="trigger" size="small" type="primary">
点击上传
<i class="el-icon-upload el-icon--right" />
</el-button>
<slot />
</el-upload>
<div>
<div v-for="(item, index) in fileLists" :key="index">
<span style="font-size: 8px"
>{{ item.attachName }}
<a style="color: blue" @click="privew(item)">预览</a></span
>
<span style="font-size: 8px">
<a style="color: blue" @click="delfile(item)">删除</a></span
>
</div>
</div>
</div>
</template>
<script>
import request from "@/public/utils/request";
import {
getQymhToken,
getToken,
removeQymhToken,
removeToken,
} from "@/public/utils/auth";
export default {
name: "MessageUpload",
props: {
// 附件上传url不传默认走系统附件上传地址
uploadUrl: {
type: String,
default: "/system/attach",
},
certNo: {
type: String,
default: "",
},
// 上传文件额外携带的参数
data: {
type: Object,
default: function () {
return {};
},
},
// 文件列表
fileList: {
type: Array,
default: function () {
return [];
},
},
// 文件上传成功回调函数
fileSuccess: {
type: Function,
default: function () {
return () => {};
},
},
// 文件上传前回调(判断文件后缀和大小等返回false终止上传)
beforeUpload: {
type: Function,
default: function (file) {
return () => {
return true;
};
},
},
// 文件上传限制的系统字典键
dictType: {
type: String,
default: "",
},
// 文件上传限制
fileaccept: {
type: String,
default: "",
},
//文件的ID
reportId: {
type: String,
default: "",
},
filedomain: {
type: String,
default: "",
},
filebusinessId: {
type: String,
default: "",
},limitfile:{
type: Number,
default: 1 ,
}
},
data() {
return {
url: "",
headers: { AuthQymh: "Bearer " + getQymhToken() },
loading: false,
// 显示搜索条件
showSearch: true,
// 显示全部搜索条件
isFullcondition: false,
businessId: null,
domain: null,
accept: null,
queryParams: {
pageNum: 1,
pageSize: 10,
businessId: null,
domain: null,
},
fileLists: [],
pdfUrl: "",
limit:0,
};
},
created() {
this.url = process.env.VUE_APP_BASE_API + this.uploadUrl;
this.data.isOne = false;
this.data.ownerId = this.dictType;
this.businessId = this.filebusinessId;
this.domain = this.filedomain;
this.accept = this.fileaccept;
this.limit = this.limitfile;
},
methods: {
// 文件上传成功回调
success(response, file, fileLists) {
this.loading = false;
this.fileSuccess(response, file, fileLists);
if (response.code == 200) {
this.msgSuccess("附件上传成功");
console.log(response);
this.fileLists.push({
id: response.data.id,
attachName: response.data.attachName,
suffix: response.data.suffix,
});
this.sendtoFather();
this.$refs.upload.clearFiles();
} else {
this.msgError("附件上传失败----" + response.msg);
}
},
// 文件上传时回调
progress() {
this.loading = true;
},
error(err) {
this.msgError(err);
this.loading = false;
},
fileBeforeUpload(file) {
console.log(this.fileLists.length)
if (this.fileLists.length<this.limit) {
return this.beforeUpload(file);
} else {
this.msgError("只允许上传"+this.limit+"个附件");
return false;
}
},
/** 搜索按钮操作 */
handleQuery() {},
/** 重置按钮操作 */
resetQuery() {
this.resetForm("queryForm");
this.handleQuery();
},
privew(item) {
//文件后缀如果是pdf直接预览
const loading = this.$loading({
lock: true,
text: "正在加载",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
if (item.suffix == "pdf") {
console.log(item.id);
request({
url: "/web/reportTableProd/showPdf",
method: "get",
params: { id: item.id },
responseType: "arraybuffer", //一定要设置响应类型,否则页面会是空白pdf
})
.then((res) => {
const binaryData = [];
binaryData.push(res);
//获取blob链接
this.pdfUrl = window.URL.createObjectURL(
new Blob(binaryData, { type: "application/pdf" })
);
window.open(this.pdfUrl);
window.URL.revokeObjectURL(this.pdfUrl);
})
.finally(() => {
loading.close();
});
} else {
//文件后缀不为pdf,转为pdf后预览
request({
method: "GET",
url:
"/web/reportTableProd/download/" +
item.id +
"?transferPDF=" +
"false",
responseType: "arraybuffer",
})
.then((res) => {
console.log(res);
// 获取文件名后缀
// 判断文件是pdf还是图片
this.pdfUrl = window.URL.createObjectURL(
new Blob([res], { type: "application/pdf;chartset=UTF-8" })
);
window.open(this.pdfUrl);
window.URL.revokeObjectURL(this.pdfUrl);
})
.finally(() => {
loading.close();
});
}
},
showPreview(fileName) {
const index = fileName.lastIndexOf(".") + 1;
const fileSuffix = fileName.substring(index);
const fileSuffixs = "bmp,gif,jpg,jpeg,png,pdf,ppt,pptx,doc,docx,xls,xlsx";
const isPreview = fileSuffixs.indexOf(fileSuffix) != -1;
return { isPreview, fileSuffix };
},
delfile(item) {
request({
method: "GET",
url: "/web/reportTableProd/delfile/" + item.id,
}).then((res) => {
if (res.code == 200) {
let a = -1;
for (let i in this.fileLists) {
if (this.fileLists[i].id == item.id) {
this.fileLists.splice(i, 1);
}
}
// if (a != -1) {
// this.fileLists.splice(a, 1);
// }
this.msgSuccess("删除成功");
this.sendtoFather();
} else {
this.msgError("删除失败");
}
});
},
sendtoFather() {
this.$emit("getFileList", this.fileLists);
},
},
// this.$confirm('当前页面数据还未保存,是否离开?', {
// type: 'warning',
// confirmButtonText: '确定',
// cancelButtonText: '取消',
// }).then(() => {
// for(let i in this.fileLists){
// request({
// method: "GET",
// url: "/web/reportTableProd/delfile/" + item.id,
// }).then((res)=>{
// console.log(res.msg)
// })
// }
// next()
// }).catch(() => {
// next(false)
// })
};
</script>
<style lang="scss">
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
</style>
使用方式:
<!--确保reportId传到子组件里是有值的状态-->
<div v-if="reportId" class="uploadClass">
<message-upload
uploadUrl="/web/reportTableProd/test"
fileaccept="application/pdf"
:transferPDF="true"
:beforeUpload="field101BeforeUpload"
filedomain="xxxxxx"---->文件域
:filebusinessId="reportId"
@getFileList="getFileLists"
limtfile=5---->限制上传文件数量
>
<br />
<span style="font-size: 12px; color: gray"
>请上传大小不超过8M的pdf文件</span
>
</message-upload>
后端代码
public List<SAttach> addAttachs1(List<MultipartFile> files, String businessId, String domain) {
if(files == null){
return null;
}
JcCorpInfo jcCorpInfo = QymhUserUtils.getScUser();
List<SAttach> sAttaches = new ArrayList<SAttach>();
// 添加附件信息
for (MultipartFile file : files) {
try {
SAttach sAttach = new SAttach();
sAttach.setId(IdUtils.simpleUUID());
sAttach.setBusinessId(businessId);
sAttach.setDomain(domain);
String extension = FileUploadUtils.getExtension(file);
boolean flag = FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
if (!flag) {
continue;
}
sAttach.setSuffix(extension);
String filePath = HxzkConfig.getUploadPath();
final String pathFileName;
if (!StringUtils.isEmpty(sAttach.getDomain())) {
pathFileName = FileUploadUtils.upload(filePath, file, sAttach.getDomain(), sAttach.getBusinessId());
} else {
pathFileName = FileUploadUtils.upload(filePath, file);
}
sAttach.setDelFlag("1");
sAttach.setOwnerName(jcCorpInfo.getCertNo());
sAttach.setAttachPath(pathFileName.replace("/profile", ""));
sAttach.setFilesize(String.valueOf(file.getSize()));
sAttach.setAttachName(file.getOriginalFilename());
sAttach.setSuffix(extension);
this.attachMapper.insertSAttach(sAttach);
sAttaches.add(sAttach);
} catch (IOException e) {
e.printStackTrace();
throw new BaseException("附件上传异常,请联系管理员");
}
}
return sAttaches;
}
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension, String domain, String buisnessId) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > DEFAULT_FILE_NAME_LENGTH) {
throw new FileNameLengthLimitExceededException(DEFAULT_FILE_NAME_LENGTH);
} else {
assertAllowed(file, allowedExtension);
String fileName = domain + "/" + extractFilename(file);
getAbsoluteFile(baseDir, fileName);
File destFile = new File(baseDir + "/" + fileName);
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
String pathFileName = getPathFileName(baseDir, fileName);
return pathFileName;
}
}
预览时若为doc,docx文件在后端将其转化为pdf文件后返回流,进行预览
@GetMapping("/showPdf")
public void showPdf(@RequestParam("id")String id, HttpServletResponse response) throws IOException {
SAttach sAttach = attachMapper.selectSAttachById(id);
System.out.println("====================================");
System.out.println(HxzkConfig.getProfile());
System.out.println("========================================");
String pdfPath = HxzkConfig.getProfile()+sAttach.getAttachPath();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(sAttach.getAttachName(), "UTF-8"));
FileUtils.writeBytes(pdfPath, response.getOutputStream());
File file = new File(pdfPath);
if (file.exists()) {
DataOutputStream temps = new DataOutputStream(response.getOutputStream());
DataInputStream in = new DataInputStream(new FileInputStream(pdfPath));
byte[] b = new byte[2048];
while ((in.read(b)) != -1) {
temps.write(b);
temps.flush();
}
in.close();
temps.close();
} else {
Log.error("文件不存在!");
}
}
/**
* doc文件预览时生产pdf文件
* @param id
* @param transferPDF
* @param request
* @param response
*/
@GetMapping({"download/{id}"})
public void downLoad(@PathVariable String id, @RequestParam(defaultValue = "false") boolean transferPDF, HttpServletRequest request, HttpServletResponse response) {
try {
SAttach sAttach1 = this.sAttachService.selectAttachById(id, transferPDF);
String suffix = sAttach1.getSuffix();
String fileName1 = sAttach1.getAttachPath();
String readPath = HxzkConfig.getReadPath();
String[] readPaths = readPath.split(",");
String filePath = null;
String[] var11 = readPaths;
int var12 = readPaths.length;
String fileNameOss;
for(int var13 = 0; var13 < var12; ++var13) {
fileNameOss = var11[var13];
filePath = fileNameOss + fileName1;
Boolean aBoolean = this.PdfExist(filePath);
if (!aBoolean) {
}
}
String outPath;
if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix) || "xls".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix)) {
outPath = filePath.replace(suffix, "pdf");
Boolean aBoolean = this.PdfExist(outPath);
if (!aBoolean) {
if (!"doc".equals(suffix) && !"docx".equals(suffix)) {
PdfUtils.excel2pdf(filePath, outPath);
} else {
PdfUtils.word2pdf(filePath, outPath);
}
}
}
if (null == sAttach1) {
log.error("无此附件");
return;
}
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(sAttach1.getAttachName(), "utf-8"));
FileUtils.writeBytes(filePath.replaceAll(suffix,"pdf"), response.getOutputStream());
} catch (Exception var17) {
log.error("下载文件失败", var17);
}
}
public Boolean PdfExist(String path) {
File file = new File(path);
return !file.exists() ? false : true;
}
前端预览代码
privew(item) {
//文件后缀如果是pdf直接预览
const loading = this.$loading({
lock: true,
text: "正在加载",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
if (item.suffix == "pdf") {
console.log(item.id);
request({
url: "/web/reportTableProd/showPdf",
method: "get",
params: { id: item.id },
responseType: "arraybuffer", //一定要设置响应类型,否则页面会是空白pdf
})
.then((res) => {
const binaryData = [];
binaryData.push(res);
//获取blob链接
this.pdfUrl = window.URL.createObjectURL(
new Blob(binaryData, { type: "application/pdf" })
);
window.open(this.pdfUrl);
window.URL.revokeObjectURL(this.pdfUrl);
})
.finally(() => {
loading.close();
});
} else {
//文件后缀不为pdf,转为pdf后预览
request({
method: "GET",
url:
"/web/reportTableProd/download/" +
item.id +
"?transferPDF=" +
"false",
responseType: "arraybuffer",
})
.then((res) => {
console.log(res);
// 获取文件名后缀
// 判断文件是pdf还是图片
this.pdfUrl = window.URL.createObjectURL(
new Blob([res], { type: "application/pdf;chartset=UTF-8" })
);
window.open(this.pdfUrl);
window.URL.revokeObjectURL(this.pdfUrl);
})
.finally(() => {
loading.close();
});
}
},
showPreview(fileName) {
const index = fileName.lastIndexOf(".") + 1;
const fileSuffix = fileName.substring(index);
const fileSuffixs = "bmp,gif,jpg,jpeg,png,pdf,ppt,pptx,doc,docx,xls,xlsx";
const isPreview = fileSuffixs.indexOf(fileSuffix) != -1;
return { isPreview, fileSuffix };
},
效果预览
文件与表单上传是异步的,如需要,可自己改。
当个笔记记录在此