增加图片缩略图以及Word、txt文档在线预览

文件上传组件完整代码

<template><div><el-uploadclass="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-bodytitle="预览"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 = valthis.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.idgetFileUrl(id).then(response => {let fileType = response.file.fileTypeif (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.urlthis.imgDialogVisible = true}})},initUpload() {this.fileList = this.outFileListthis.upload.fileList = this.fileListthis.form.layoutFileIdsArr = []for (let i=0; i<this.fileList.length; i++) {this.fileList[i].name = this.fileList[i].fileName + "." + this.fileList[i].fileTypethis.fileList[i].size = this.fileList[i].fileSizethis.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 = thisthis.id = this.$route.query.idgetFileUrl(this.id).then(response => {let fileType = response.file.fileTypeif (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();// 这不懂干什么用的,但是是必填,随便填个0sysFile.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());}}

vue 文件上传组件封装相关推荐

  1. Vue:利用Plupload插件封装文件上传组件

    接上回<Plupload插件>,已经尝试将Plupload插件引入到HTML页面中,并进行参数配置,然后联合后端接口进行调试,完成了文件上传的工作.但是在Vue项目的开发中,我们更想将它封 ...

  2. antd design Upload文件上传,删除,批量上传组件封装

    1.单个文件上传组件,无文件时显示上传,有文件时显示文件,可删除,重新上传,样式适合图片上传,可根据文件格式更改样式,效果图如下. 页面调用代码 <FormItem{...formItemLay ...

  3. ajax请求携带tooken_Spring Boot+Vue 文件上传,如何携带令牌信息?

    关于文件上传这块,松哥之前也写了好几篇文章了,甚至还有视频: Spring Boot+Vue+FastDFS 实现前后端分离文件上传 但是,之前和小伙伴们提到的方案,是基于 session 来做认证的 ...

  4. vue文件上传功能bootstrap框架

    vue文件上传功能bootstrap框架 封装公共组件components/fileupload/FileUpload.vue 内容如下: 公共组件 ```html <template>& ...

  5. Vue文件上传和图片上传实例

    图片上传 1.先通过组件库选择对应的文件上传组件,或者自行封装的组件,示例选的的Ant Design Vue组件库. 代码: <a-uploadaction="xxxxxxxxx&qu ...

  6. Java 文件上传组件 Apache Commons FileUpload 应用指南(二)——FileUpload如何工作?

    在最初的 http 协议中,没有上传文件方面的功能.RFC1867("Form-based File Upload in HTML".) 为 http 协议添加了这个功能.客户端的 ...

  7. 使用 Apache的文件上传组件(common-fileupload)来实现文件的上传

    文章目录 一.前言/先导 二.步骤 三.源码 四.测试结果 五.文件的下载 一.前言/先导 maven的依赖: 注意:common-fileupload,它需要依赖于 commons-io组件: &l ...

  8. 1.6 文件上传组件

    1.6 文件上传组件 1.6.1 基本形制 <input type="file" name="myfile"/> form的完整形制如下,它必须设定 ...

  9. Bootstrap fileinput.js,最好用的文件上传组件

    本篇介绍如何使用bootstrap fileinput.js(最好用的文件上传组件)来进行图片的展示,上传,包括springMVC后端文件保存. 一.demo   二.插件引入 <link ty ...

最新文章

  1. px word 表格宽度_「Word技巧」掌握这六个Word表格处理技巧,表格排版不再是问题...
  2. python3.7.4-Centos7升级Python3.7.4
  3. 什么是用户对计算机进行配置的重要工具,《计算机常用工具软件》试题1
  4. python文件命名文件夹怎么删除_python文件批量重命名、删除文件夹
  5. Static Final用法
  6. JavaScript栈的实现
  7. AWS SQS和Spring JMS集成
  8. oracle事务重要属性,Oracle中的事务(2)--属性和隔离级别
  9. VMWare 虚拟机安装及新建虚拟机
  10. 不能将紧实的字段 绑定到_紫光芯城市政配套建设项目样板段预计下月完成
  11. MySQL驱动包下载
  12. 编个故事,骗700元的稿费真容易啊!
  13. 吃透JAVA的Stream流操作,多年实践总结
  14. 同步辐射X射线断层扫描成像在各行业的应用
  15. 苹果鼠标怎么充电_“智能”还是“多功能”?米物智能鼠标垫测评
  16. QT QMdiArea的介绍
  17. 中国就业薪酬最高的十所大学
  18. 计算机各外设的作用,外设在计算机中的作用及传输方式.doc
  19. [samba]Samba服务器架设
  20. 纯CSS实现逼真翻页时钟

热门文章

  1. 如何使用Python创建AI虚拟助手
  2. 复分析阿尔福斯下载中文_《复分析(原书第3版)》([美]阿尔福斯(Ahlfors,L.V.))【摘要 书评 试读】- 京东图书...
  3. 电子元器件与设计库(原理图库、PCB库)的关系
  4. you-get简明使用教程
  5. 记一下virtualbox的扩展包extension pack 包老是失败的问题
  6. cocos2dx点击和键盘事件
  7. Part 2.2 离散类别值与连续值
  8. 用js实现高清放大图片效果
  9. 用友畅捷通升级时提示“T3账套采购或销售是优化流程,不支持升级处理”
  10. Windows 2008 修改或取消密码安全策略