增加图片缩略图以及Word、txt文档在线预览
文件上传组件完整代码
<template>
<div>
<el-upload
class="upload-demo"
:action="upload.url"
:headers="upload.headers"
:on-change="handleUploadChange"
:on-success="handleUploadSuccess"
:on-remove="handleUploadRemove"
:on-preview="handleUploadPreview"
:before-upload="beforeUpload"
:file-list="upload.fileList"
:disabled="disabled" >
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<el-dialog
:visible.sync="imgDialogVisible"
append-to-body
title="预览"
width="800"
>
<img
:src="dialogImageUrl"
style="display: block; max-width: 100%; margin: 0 auto"
/>
</el-dialog>
</div>
</template>
<script>
import { getFileUrl } from '@/api/system/file'
import { getToken } from '@/utils/auth'
export default {
name: 'UploadCommon',
props: {
outFileList: {
type: Array,
default: () => []
},
disabled: {
type: Boolean,
default: () => false
},
finishUploadChange: {
type: Function
},
},
watch: {
outFileList(val) {
this.fileList = val
this.initUpload()
}
},
data() {
return {
// 文件上传配置
upload: {
// 是否禁用上传
isUploading: false,
// 设置上传的请求头部
headers: { Authorization: "Bearer " + getToken() },
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/common/uploadGetId",
// 上传的文件列表
fileList: []
},
form: {
layoutFileIds: null,
layoutFileIdsArr: []
},
fileList: [],
dialogImageUrl: "",
imgDialogVisible: false
}
},
methods: {
handleUploadChange(file, fileList) {
this.fileList = fileList.slice(-3);
},
handleUploadRemove(file, fileList, event) {
console.log(file)
this.form.layoutFileIdsArr.splice(this.form.layoutFileIdsArr.indexOf(file.id), 1)
this.form.layoutFileIds = this.form.layoutFileIdsArr.join(",")
this.finishUploadChange(this.form.layoutFileIds)
},
handleUploadSuccess(response, file, fileList) {
this.form.layoutFileIdsArr.push(response.id)
this.form.layoutFileIds = this.form.layoutFileIdsArr.join(",").toString()
this.finishUploadChange(this.form.layoutFileIds);
},
resetFileList() {
this.fileList = []
},
beforeUpload(file) {
console.log(file)
let isJPG = file.type === 'image/jpeg';
let isTxt = file.type === 'text/plain';
let isWord = ( file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|| file.type === 'application/msword' );
let isPdf = file.type === 'application/pdf';
// const isLt2M = file.size / 1024 / 1024 < 2;
if (! (isJPG || isTxt || isWord || isPdf)) {
this.$message.error('上传文件只能是 JPG、TXT、Word、PDF 格式!');
}
// if (!isLt2M) {
// this.$message.error('上传头像图片大小不能超过 2MB!');
// }
return isJPG || isTxt || isWord || isPdf;
},
handleUploadPreview(file) {
let id = file.id ? file.id : file.response.id
getFileUrl(id).then(response => {
let fileType = response.file.fileType
if (fileType === 'pdf' || fileType === 'txt') {
window.open(response.file.url)
} else if (fileType === 'docx' || fileType === 'doc') {
// window.location.href = './wordPreview?id=' + id;
window.open('/backstage/emergency/wordPreview?id=' + id)
} else if (fileType === 'jpg') {
this.dialogImageUrl = response.file.url
this.imgDialogVisible = true
}
})
},
initUpload() {
this.fileList = this.outFileList
this.upload.fileList = this.fileList
this.form.layoutFileIdsArr = []
for (let i=0; i<this.fileList.length; i++) {
this.fileList[i].name = this.fileList[i].fileName + "." + this.fileList[i].fileType
this.fileList[i].size = this.fileList[i].fileSize
this.form.layoutFileIdsArr.push(this.fileList[i].id)
}
this.form.layoutFileIds = this.form.layoutFileIdsArr.join(",")
console.log(this.fileList)
}
},
created() {
this.initUpload()
}
}
</script>
<style scoped>
</style>
文档在线预览组件完整代码,此处使用 mammoth 作为word文档预览插件
<template>
<div class="word-wrap">
<div id="wordView" v-html="wordText" />
</div>
</template>
<script>
// docx文档预览(只能转换.docx文档,转换过程中复杂样式被忽,居中、首行缩进等)
import mammoth from "mammoth";
import { getFileUrl } from '@/api/system/file'
export default {
name: "EnterpriseWordPreview",
data() {
return {
id: Number,
wordText: "",
wordURL: ''//文件地址
};
},
created() {
this.getWord();
this.getWordText();
},
methods: {
getWord() {
let _this = this
this.id = this.$route.query.id
getFileUrl(this.id).then(response => {
let fileType = response.file.fileType
if (fileType === 'docx' || fileType === 'doc') {
// window.location.href = './wordPreview?id=' + id;
// console.log(response.file.fileName + "." + fileType)
_this.wordURL = response.file.url
_this.getWordText()
} else {
_this.wordText = "当前文档格式不正确"
}
})
},
getWordText() {
let xhr = new XMLHttpRequest();
xhr.open("get", this.wordURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = () => {
if (xhr.status === 200) {
mammoth.convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) }).then((resultObject) => {
this.$nextTick(() => {
this.wordText = resultObject.value;
});
});
}
};
xhr.send();
}
},
};
</script>
<style>
.word-wrap {
padding: 15px;
}
.word-wrap img {
width: 100%;
}
</style>
父组件中用法
<el-form-item label="相关附件:" prop="hazardousRegeditFileId">
<upload-common
:disabled="disabled"
:finish-upload-change="finishUploadChange"
:out-file-list="fileList" >
</upload-common>
</el-form-item>
finishUploadChange(ids) {
this.form.layoutFileIds = ids
},
后端文件上传Java代码
@ApiOperation("通用上传请求返回文件表id")
@ApiImplicitParam(name = "file", value = "文件流", dataType = "MultipartFile")
@PostMapping("/common/uploadGetId")
public AjaxResult uploadGetId(MultipartFile file) {
try {
// 上传文件路径
String filePath = KingTopConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String realName = file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf("."));
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("fileName", realName);
ajax.put("url", url);
String localFilePath = filePath + fileName.substring(fileName.indexOf("/upload")+7);
// 存储到文件表
SysFile sysFile = new SysFile();
// 这不懂干什么用的,但是是必填,随便填个0
sysFile.setTableId(0l);
sysFile.setDataId(0l);
sysFile.setMark(IdUtils.simpleUUID());
sysFile.setUserId(SecurityUtils.getUserId());
sysFile.setUserName(SecurityUtils.getUsername());
sysFile.setUploadTime(new Date());
sysFile.setUrl(url);
sysFile.setFileSize(file.getSize());
sysFile.setFileName(realName);
sysFile.setFilePath(localFilePath);
sysFile.setFileType(url.substring(url.lastIndexOf(".")+1));
sysFile.setFileMd5(SecureUtil.md5(new File(localFilePath)));
sysFile.setStatus(0l);
ajax.put("id", sysFileService.insertSysFile(sysFile));
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}