当前位置:   article > 正文

SpringBoot+Vue+OpenOffice实现文档管理(文档上传、下载、在线预览)_springboot+vue+onlyoffice开发在线编辑文档

springboot+vue+onlyoffice开发在线编辑文档

场景

SpringBoot集成OpenOffice实现doc文档转html:

SpringBoot集成OpenOffice实现doc文档转html_BADAO_LIUMANG_QIZHI的博客-CSDN博客

在上面初步使用了OpenOffice之后,怎样实现文档管理,文档上传、下载、在线预览等。

首先OpenOffice的下载安装与启动服务参照上文,不再复述。

注:

博客:
BADAO_LIUMANG_QIZHI的博客_霸道流氓气质_CSDN博客
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

1、搭建SpringBoot+Vue前后端分离项目

若依前后端分离版本地搭建开发环境并运行项目的教程:

若依前后端分离版手把手教你本地搭建环境并运行项目_BADAO_LIUMANG_QIZHI的博客-CSDN博客

2、设计表

数据库语句为

  1. DROP TABLE IF EXISTS `bus_file_preview`;
  2. CREATE TABLE `bus_file_preview`  (
  3.   `id` bigint(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
  4.   `fileName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '原文件名(上传前文件名)',
  5.   `fileType` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件后缀(.xls;.xlsx;.ppt;.doc;.docx;.pptx)',
  6.   `uploadPath` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上传后文件路径',
  7.   `uploadFileName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上传后文件名',
  8.   `pdfPath` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '转换pdf路径',
  9.   `pdfName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '转换pdf文件名',
  10.   `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  11.   `create_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '创建人',
  12.   `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
  13.   `update_by` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '更新人',
  14.   `remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '备注',
  15.   `preview_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '预览URL',
  16.   PRIMARY KEY (`id`) USING BTREE
  17. ) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '文件上传与预览' ROW_FORMAT = Dynamic;
  18. SET FOREIGN_KEY_CHECKS = 1;

依照此表生成前后端代码,然后修改代码。

3、文件上传实现

前端按钮

  1.         <el-form-item label="附件" prop="photoPath">
  2.           <el-upload
  3.             :headers="headers"
  4.             :action="url"
  5.             :multiple="false"
  6.             :file-list="fileList"
  7.             :on-remove="fileRemove"
  8.             :on-success="uploadSuccess"
  9.             :on-error="uploadError"
  10.             :on-progress="uploadProgress"
  11.             :before-upload="beforeUpload"
  12.             :limit="1"
  13.             :on-exceed="beyond"
  14.             accept=".doc,.docx,.xls,.ppt,.xlsx,.pptx"
  15.           >
  16.             <el-button size="small">
  17.               上传
  18.               <i class="el-icon-upload el-icon--right"></i>
  19.             </el-button>
  20.             <div class="el-upload__tip" style="color: red" slot="tip">
  21.               提示:仅允许导入“.doc、.docx、.xls、.ppt、.xlsx、.pptx”格式文件!
  22.             </div>
  23.           </el-upload>
  24.         </el-form-item>

调用的各方法

  1.     // 文件上传失败
  2.     uploadError(err) {
  3.       this.btnLoding = false;
  4.       this.$message.error(res.msg);
  5.     },
  6.     // 上传中
  7.     uploadProgress(e) {
  8.       this.btnLoding = true;
  9.     },
  10.     // 文件上传之前
  11.     beforeUpload(file) {
  12.       console.log(file, "上传之前");
  13.       const fileName = file.name;
  14.       const fileType = fileName.substring(fileName.lastIndexOf("."));
  15.       if (
  16.         fileType === ".doc" ||
  17.         fileType === ".docx" ||
  18.         fileType === ".xls" ||
  19.         fileType === ".ppt" ||
  20.         fileType === ".pptx" ||
  21.         fileType === ".xlsx"
  22.       ) {
  23.         this.form.filename = file.name;
  24.         // 不处理
  25.       } else {
  26.         this.$message.error("请上传正确的文件类型,.doc,.docx,.xls,.ppt,.xlsx,.pptx,");
  27.         return false;
  28.       }
  29.     },
  30.     // 文件上传成功
  31.     uploadSuccess(res, file, fileList) {
  32.       this.form.uploadpath = res.uploadpath;
  33.       this.btnLoding = false;
  34.       this.fileList = fileList;
  35.       this.$message(res.msg);
  36.     },
  37.     beyond(file, fileList) {
  38.       this.$message({
  39.         message: "最多上传一个文件",
  40.         type: "warning",
  41.       });
  42.     },
  43.     // 移除选择的文件
  44.     fileRemove(file, fileList) {
  45.       this.btnLoding = false;
  46.       this.reset();
  47.       this.fileList = [];
  48.     },

对应后台SpingBoot通用上传接口

这里做了修改,使其能返回磁盘路径

  1.     /**
  2.      * 通用上传请求返回磁盘路径
  3.      */
  4.     @PostMapping("/common/uploadWithAbsolutePath")
  5.     public AjaxResult uploadFileWithAbsolutePath(MultipartFile file) throws Exception
  6.     {
  7.         try
  8.         {
  9.             // 上传文件路径
  10.             String filePath = RuoYiConfig.getUploadPath();
  11.             // 上传并返回新文件名称
  12.             String fileName = FileUploadUtils.uploadWithAbsolutePath(filePath, file);
  13.             AjaxResult ajax = AjaxResult.success();
  14.             ajax.put("uploadpath", filePath+ File.separator+fileName);
  15.             return ajax;
  16.         }
  17.         catch (Exception e)
  18.         {
  19.             return AjaxResult.error(e.getMessage());
  20.         }
  21.     }

调用的方法uploadWithAbsolutePath实现

  1.     public static final String uploadWithAbsolutePath(String baseDir, MultipartFile file) throws IOException
  2.     {
  3.         try
  4.         {
  5.             return uploadWithAbsolutePath(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
  6.         }
  7.         catch (Exception e)
  8.         {
  9.             throw new IOException(e.getMessage(), e);
  10.         }
  11.     }

其中又调用的uploadWithAbsolutePath方法实现

  1.     public static final String uploadWithAbsolutePath(String baseDir, MultipartFile file, String[] allowedExtension)
  2.             throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
  3.             InvalidExtensionException
  4.     {
  5.         int fileNamelength = file.getOriginalFilename().length();
  6.         if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
  7.         {
  8.             throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
  9.         }
  10.         assertAllowed(file, allowedExtension);
  11.         String fileName = extractFilename(file);
  12.         File desc = getAbsoluteFile(baseDir, fileName);
  13.         file.transferTo(desc);
  14.         return fileName;
  15.     }

其他的若依框架原来的方法。

上传效果

4、预览实现

上传之后的文件转换成pdf的实现,在提交按钮时调用后台就接口

  1.     /** 提交按钮 */
  2.     submitForm() {
  3.       this.$refs["form"].validate((valid) => {
  4.         if (valid) {
  5.           if (this.form.id != null) {
  6.             updatePreview(this.form).then((response) => {
  7.               this.msgSuccess("修改成功");
  8.               this.open = false;
  9.               this.fileList = [];
  10.               this.getList();
  11.             });
  12.           } else {
  13.             addPreview(this.form).then((response) => {
  14.               this.msgSuccess("新增成功");
  15.               this.open = false;
  16.               this.fileList = [];
  17.               this.getList();
  18.             });
  19.           }
  20.         }
  21.       });
  22.     },

首先是新增接口

  1.     /**
  2.      * 新增preview
  3.      */
  4.     @Log(title = "preview", businessType = BusinessType.INSERT)
  5.     @PostMapping
  6.     public AjaxResult add(@RequestBody BusFilePreview busFilePreview) throws IOException{
  7.         if (StringUtils.isNull(busFilePreview.getFilename())) {
  8.             AjaxResult.error("缺少文件名称");
  9.         }
  10.         if (StringUtils.isNull(busFilePreview.getUploadpath())) {
  11.             AjaxResult.error("缺少上传文件路径");
  12.         }
  13.         String substringAfter = StringUtils.substringAfter(busFilePreview.getUploadpath(), ".");
  14.         String upName = StringUtils.substringAfterLast(busFilePreview.getUploadpath(), "/");
  15.         busFilePreview.setUploadfilename(upName);
  16.         busFilePreview.setFiletype(substringAfter); //类型
  17.         if ("pdf".equals(substringAfter)){
  18.             FilePdfUtils.copyFile(busFilePreview.getUploadpath(), RuoYiConfig.getProfile());
  19.             String pdfName = StringUtils.substringAfterLast(busFilePreview.getUploadpath(), "/");
  20.             busFilePreview.setPdfpath(RuoYiConfig.getProfile()+ "/" + pdfName);
  21.             busFilePreview.setPdfname(pdfName);
  22.             return  toAjax(busFilePreviewService.insertBusFilePreview(busFilePreview));
  23.         }
  24.         File file = new File(busFilePreview.getUploadpath());
  25.         FileInputStream fileInputStream = new FileInputStream(file);
  26.         String htmFileName = FilePdfUtils.file2pdf(fileInputStream, substringAfter,RuoYiConfig.getProfile());
  27.         String pdfPath = RuoYiConfig.getProfile()+ "/" + htmFileName;
  28.         busFilePreview.setPdfpath(pdfPath);
  29.         String pdfName = StringUtils.substringAfterLast(pdfPath, "/");
  30.         busFilePreview.setPdfname(pdfName);
  31.         String previewUrl = serverConfig.getUrl()+ Constants.RESOURCE_PREFIX+File.separator+htmFileName;
  32.         busFilePreview.setPreviewUrl(previewUrl);
  33.         return toAjax(busFilePreviewService.insertBusFilePreview(busFilePreview));
  34.     }

这里调用了工具类中FilePdfUtils的file2pdf方法,并且将转换后的pdf的路径拼接成静态资源映射后的路径返回给前端。

关于静态资源映射可以参考如下

SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url:

SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url_BADAO_LIUMANG_QIZHI的博客-CSDN博客

5、FilePdfUtils工具类实现

  1. package com.ruoyi.common.utils.pdf;
  2. import com.artofsolving.jodconverter.DocumentConverter;
  3. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
  4. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
  5. import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
  6. import com.ruoyi.common.utils.StringUtils;
  7. import java.io.*;
  8. import java.net.ConnectException;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. public class FilePdfUtils {
  12.     /**
  13.      * 转换文件成pdf
  14.      *
  15.      * @param fromFileInputStream:
  16.      * @throws IOException
  17.      */
  18.     public static String file2pdf(InputStream fromFileInputStream, String type,String pdfPath) throws IOException {
  19.         Date date = new Date();
  20.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  21.         String timesuffix = sdf.format(date);
  22.         String docFileName = null;
  23.         String htmFileName = null;
  24.         if("doc".equals(type)){
  25.             docFileName = "doc_" + timesuffix + ".doc";
  26.             htmFileName = "doc_" + timesuffix + ".pdf";
  27.         }else if("docx".equals(type)){
  28.             docFileName = "docx_" + timesuffix + ".docx";
  29.             htmFileName = "docx_" + timesuffix + ".pdf";
  30.         }else if("xls".equals(type)){
  31.             docFileName = "xls_" + timesuffix + ".xls";
  32.             htmFileName = "xls_" + timesuffix + ".pdf";
  33.         }else if("ppt".equals(type)){
  34.             docFileName = "ppt_" + timesuffix + ".ppt";
  35.             htmFileName = "ppt_" + timesuffix + ".pdf";
  36.         }else if("xlsx".equals(type)){
  37.             docFileName = "xlsx_" + timesuffix + ".xlsx";
  38.             htmFileName = "xlsx_" + timesuffix + ".pdf";
  39.         }else if("pptx".equals(type)){
  40.             docFileName = "pptx_" + timesuffix + ".pptx";
  41.             htmFileName = "pptx_" + timesuffix + ".pdf";
  42.         }else{
  43.             return null;
  44.         }
  45.         check_folder(pdfPath);
  46.         File htmlOutputFile = new File(pdfPath + File.separatorChar + htmFileName);
  47.         File docInputFile = new File(pdfPath + File.separatorChar + docFileName);
  48.         if (htmlOutputFile.exists())
  49.             htmlOutputFile.delete();
  50.         htmlOutputFile.createNewFile();
  51.         if (docInputFile.exists())
  52.             docInputFile.delete();
  53.         docInputFile.createNewFile();
  54.         /**
  55.          * 由fromFileInputStream构建输入文件
  56.          */
  57.         try {
  58.             OutputStream os = new FileOutputStream(docInputFile);
  59.             int bytesRead = 0;
  60.             byte[] buffer = new byte[1024 * 8];
  61.             while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
  62.                 os.write(buffer, 0, bytesRead);
  63.             }
  64.             os.close();
  65.             fromFileInputStream.close();
  66.         } catch (IOException e) {
  67.         }
  68.         OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
  69.         try {
  70.             connection.connect();
  71.         } catch (ConnectException e) {
  72.             System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");
  73.         }
  74.         DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
  75.         converter.convert(docInputFile, htmlOutputFile);
  76.         connection.disconnect();
  77.         // 转换完之后删除word文件
  78.         docInputFile.delete();
  79.         System.out.println(htmFileName);
  80.         return htmFileName;
  81.     }
  82.     public static void check_folder(String path) {
  83.         File dir = new File(path);
  84.         // 判断文件夹是否存在
  85.         if (dir.isDirectory()) {
  86.         } else {
  87.             dir.mkdirs();
  88.         }
  89.     }
  90.     public static void copyFile(String oldPath, String newPath) throws IOException {
  91.         File oldFile = new File(oldPath);//获取旧的文件File对象
  92.         File file = new File(newPath + oldFile.separator + StringUtils.substringAfterLast(oldPath, "/"));  //获取新的文件File对象并生成文件
  93.         FileInputStream in = new FileInputStream(oldFile);  //
  94.         FileOutputStream out = new FileOutputStream(file);
  95.         byte[] buffer=new byte[2097152];
  96.         int readByte = 0;
  97.         //读取旧文件的流写入新文件里
  98.         while((readByte = in.read(buffer)) != -1){
  99.             out.write(buffer, 0, readByte);
  100.         }
  101.         in.close();
  102.         out.close();
  103.     }
  104. }

注意这里的连接openOffice的服务的端口要对应并且确保openOffice已经启动

 然后工具类FilePdfUtils是在common模块下,所以后台需要在此模块下pom文件中添加依赖

  1.         <dependency>
  2.             <groupId>com.artofsolving</groupId>
  3.             <artifactId>jodconverter</artifactId>
  4.             <version>2.2.1</version>
  5.         </dependency>

添加位置

注意这里的版本为2.2.1,Maven中央仓库中此为最高版本

这里在调用工具类转换文件时,如果文件类型为docx、pptx、xlsx时会报错提示

unknown document format for file ....docx

这是因为2.2.1的能转换doc ,但2.2.2才能转换docx,如果你用2.2.1的jar包,转换2.2.2的docx文档就会出错

除了不加载Maven中央仓库的2.1的依赖之外,还可以重写DocumentFormatRegistry接口的getFormatByFileExtension方法

注意包名一致

  1. package com.artofsolving.jodconverter;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. /**
  6.  * @ClassName: online
  7.  * @description: 重写 BasicDocumentFormatRegistry 文档格式
  8.  * @Author: yandongfa
  9.  * @Data: 2020-03-24 19:47
  10.  * @Version: 1.0
  11.  **/
  12. public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
  13.     private List/* <DocumentFormat> */ documentFormats = new ArrayList();
  14.     public void addDocumentFormat(DocumentFormat documentFormat) {
  15.         documentFormats.add(documentFormat);
  16.     }
  17.     protected List/* <DocumentFormat> */ getDocumentFormats() {
  18.         return documentFormats;
  19.     }
  20.     /**
  21.      * @param extension
  22.      *            the file extension
  23.      * @return the DocumentFormat for this extension, or null if the extension
  24.      *         is not mapped
  25.      */
  26.     public DocumentFormat getFormatByFileExtension(String extension) {
  27.         if (extension == null) {
  28.             return null;
  29.         }
  30.         //new DefaultDocumentFormatRegistry();
  31.         //将文件名后缀统一转化
  32.         if (extension.indexOf("doc") >= 0) {
  33.             extension = "doc";
  34.         }
  35.         if (extension.indexOf("ppt") >= 0) {
  36.             extension = "ppt";
  37.         }
  38.         if (extension.indexOf("xls") >= 0) {
  39.             extension = "xls";
  40.         }
  41.         String lowerExtension = extension.toLowerCase();
  42.         for (Iterator it = documentFormats.iterator(); it.hasNext();) {
  43.             DocumentFormat format = (DocumentFormat) it.next();
  44.             if (format.getFileExtension().equals(lowerExtension)) {
  45.                 return format;
  46.             }
  47.         }
  48.         return null;
  49.     }
  50.     public DocumentFormat getFormatByMimeType(String mimeType) {
  51.         for (Iterator it = documentFormats.iterator(); it.hasNext();) {
  52.             DocumentFormat format = (DocumentFormat) it.next();
  53.             if (format.getMimeType().equals(mimeType)) {
  54.                 return format;
  55.             }
  56.         }
  57.         return null;
  58.     }
  59. }

6、在线预览实现

  1.           <el-button
  2.             size="mini"
  3.             type="text"
  4.             icon="el-icon-edit"
  5.             @click="handlePreview(scope.row)"
  6.             >预览</el-button
  7.           >

调用js方法

  1.     // 预览
  2.     handlePreview(row) {
  3.       let url = row.previewUrl;
  4.       window.open(url);
  5.     },

这里直接打开url这个字段对应的地址即可,url是在进行文件转换成pdf时生成的映射的服务器上的url

String previewUrl = serverConfig.getUrl()+ Constants.RESOURCE_PREFIX+File.separator+htmFileName;

注意这里的预览地址如果有拦截,让在后台配置中放开白名单。

7、文件下载实现

  1.     // 下载
  2.     handleDownload(row) {
  3.       const baseURL = process.env.VUE_APP_BASE_API
  4.       window.location.href = baseURL + "/common/download/resourceeasy?resource=" + encodeURI(row.uploadpath);
  5.     },

这里直接修改后台的下载本地资源的通用下载方法

  1.     @GetMapping("/common/download/resourceeasy")
  2.     public void resourceDownloadEasy(String resource, HttpServletRequest request, HttpServletResponse response)
  3.             throws Exception
  4.     {
  5.         try
  6.         {
  7.             if (!FileUtils.checkAllowDownload(resource))
  8.             {
  9.                 throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
  10.             }
  11.             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  12.             FileUtils.setAttachmentResponseHeader(response, resource);
  13.             FileUtils.writeBytes(resource, response.getOutputStream());
  14.         }
  15.         catch (Exception e)
  16.         {
  17.             log.error("下载文件失败", e);
  18.         }
  19.     }

下载效果

8、各层完整代码

前端完整代码

  1. <template>
  2.   <div class="app-container">
  3.     <el-form
  4.       :model="queryParams"
  5.       ref="queryForm"
  6.       :inline="true"
  7.       v-show="showSearch"
  8.       label-width="68px"
  9.     >
  10.       <el-form-item label="原文件名" prop="filename">
  11.         <el-input
  12.           v-model="queryParams.filename"
  13.           placeholder="请输入原文件名"
  14.           clearable
  15.           size="small"
  16.           @keyup.enter.native="handleQuery"
  17.         />
  18.       </el-form-item>
  19.       <el-form-item>
  20.         <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery"
  21.           >搜索</el-button
  22.         >
  23.         <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
  24.       </el-form-item>
  25.     </el-form>
  26.     <el-row :gutter="10" class="mb8">
  27.       <el-col :span="1.5">
  28.         <el-button
  29.           type="primary"
  30.           icon="el-icon-plus"
  31.           size="mini"
  32.           @click="handleAdd"
  33.           v-hasPermi="['basicinfomanage:preview:add']"
  34.           >新增</el-button
  35.         >
  36.       </el-col>
  37.       <el-col :span="1.5">
  38.         <el-button
  39.           type="success"
  40.           icon="el-icon-edit"
  41.           size="mini"
  42.           :disabled="single"
  43.           @click="handleUpdate"
  44.           v-hasPermi="['basicinfomanage:preview:edit']"
  45.           >修改</el-button
  46.         >
  47.       </el-col>
  48.       <el-col :span="1.5">
  49.         <el-button
  50.           type="danger"
  51.           icon="el-icon-delete"
  52.           size="mini"
  53.           :disabled="multiple"
  54.           @click="handleDelete"
  55.           v-hasPermi="['basicinfomanage:preview:remove']"
  56.           >删除</el-button
  57.         >
  58.       </el-col>
  59.       <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
  60.     </el-row>
  61.     <el-table
  62.       v-loading="loading"
  63.       :data="previewList"
  64.       @selection-change="handleSelectionChange"
  65.     >
  66.       <el-table-column type="selection" width="55" align="center" />
  67.       <el-table-column
  68.         show-overflow-tooltip
  69.         label="文件名"
  70.         align="center"
  71.         prop="filename"
  72.       />
  73.       <el-table-column
  74.         show-overflow-tooltip
  75.         label="上传后文件路径"
  76.         align="center"
  77.         prop="uploadpath"
  78.       />
  79.       <el-table-column
  80.         show-overflow-tooltip
  81.         label="转换pdf路径"
  82.         align="center"
  83.         prop="pdfpath"
  84.         width="400"
  85.       />
  86.        <el-table-column
  87.         show-overflow-tooltip
  88.         label="预览地址"
  89.         align="center"
  90.         prop="previewUrl"
  91.         width="400"
  92.       />
  93.       <el-table-column show-overflow-tooltip label="备注" align="center" prop="remark" />
  94.       <el-table-column
  95.         label="操作"
  96.         align="center"
  97.         class-name="small-padding fixed-width"
  98.         width="200"
  99.       >
  100.         <template slot-scope="scope">
  101.           <el-button
  102.             size="mini"
  103.             type="text"
  104.             icon="el-icon-edit"
  105.             @click="handleUpdate(scope.row)"
  106.             v-hasPermi="['basicinfomanage:preview:edit']"
  107.             >修改</el-button
  108.           >
  109.           <el-button
  110.             size="mini"
  111.             type="text"
  112.             icon="el-icon-edit"
  113.             @click="handlePreview(scope.row)"
  114.             >预览</el-button
  115.           >
  116.           <el-button
  117.             size="mini"
  118.             type="text"
  119.             icon="el-icon-edit"
  120.             @click="handleDownload(scope.row)"
  121.             >下载</el-button
  122.           >
  123.           <el-button
  124.             size="mini"
  125.             type="text"
  126.             icon="el-icon-delete"
  127.             @click="handleDelete(scope.row)"
  128.             v-hasPermi="['basicinfomanage:preview:remove']"
  129.             >删除</el-button
  130.           >
  131.         </template>
  132.       </el-table-column>
  133.     </el-table>
  134.     <pagination
  135.       v-show="total > 0"
  136.       :total="total"
  137.       :page.sync="queryParams.pageNum"
  138.       :limit.sync="queryParams.pageSize"
  139.       @pagination="getList"
  140.     />
  141.     <!-- 添加或修改preview对话框 -->
  142.     <el-dialog :title="title" :visible.sync="open" width="35%" append-to-body>
  143.       <el-form ref="form" :model="form" :rules="rules" label-width="110px">
  144.         <el-form-item label="文件名" prop="filename">
  145.           <el-input v-model="form.filename" placeholder="请输入文件名" disabled />
  146.         </el-form-item>
  147.         <el-form-item label="上传后文件路径" prop="uploadpath">
  148.           <el-input v-model="form.uploadpath" placeholder="请输入上传后文件名" disabled />
  149.         </el-form-item>
  150.         <el-form-item label="备注" prop="remark">
  151.           <el-input v-model="form.remark" placeholder="请输入备注"  />
  152.         </el-form-item>
  153.         <el-form-item label="附件" prop="photoPath">
  154.           <el-upload
  155.             :headers="headers"
  156.             :action="url"
  157.             :multiple="false"
  158.             :file-list="fileList"
  159.             :on-remove="fileRemove"
  160.             :on-success="uploadSuccess"
  161.             :on-error="uploadError"
  162.             :on-progress="uploadProgress"
  163.             :before-upload="beforeUpload"
  164.             :limit="1"
  165.             :on-exceed="beyond"
  166.             accept=".doc,.docx,.xls,.ppt,.xlsx,.pptx"
  167.           >
  168.             <el-button size="small">
  169.               上传
  170.               <i class="el-icon-upload el-icon--right"></i>
  171.             </el-button>
  172.             <div class="el-upload__tip" style="color: red" slot="tip">
  173.               提示:仅允许导入“.doc、.docx、.xls、.ppt、.xlsx、.pptx”格式文件!
  174.             </div>
  175.           </el-upload>
  176.         </el-form-item>
  177.       </el-form>
  178.       <div slot="footer" class="dialog-footer">
  179.         <el-button type="primary" @click="submitForm">确 定</el-button>
  180.         <el-button @click="cancel">取 消</el-button>
  181.       </div>
  182.     </el-dialog>
  183.   </div>
  184. </template>
  185. <script>
  186. import {
  187.   listPreview,
  188.   getPreview,
  189.   delPreview,
  190.   addPreview,
  191.   updatePreview,
  192. } from "@/api/system/preview";
  193. import { getToken } from "@/utils/auth";
  194. export default {
  195.   name: "preview",
  196.   data() {
  197.     return {
  198.       // 遮罩层
  199.       loading: true,
  200.       // 选中数组
  201.       ids: [],
  202.       // 非单个禁用
  203.       single: true,
  204.       // 非多个禁用
  205.       multiple: true,
  206.       // 显示搜索条件
  207.       showSearch: true,
  208.       // 总条数
  209.       total: 0,
  210.       // preview表格数据
  211.       previewList: [],
  212.       // 弹出层标题
  213.       title: "",
  214.       // 是否显示弹出层
  215.       open: false,
  216.       // 查询参数
  217.       queryParams: {
  218.         pageNum: 1,
  219.         pageSize: 10,
  220.         filename: null,
  221.         filetype: null,
  222.         uploadpath: null,
  223.         pdfpath: null,
  224.         pdfname: null,
  225.       },
  226.       // 表单参数
  227.       form: {},
  228.       // 表单校验
  229.       rules: {
  230.         filename: [
  231.           {
  232.             required: true,
  233.             message: "文件名称不能为空",
  234.             trigger: "blur",
  235.           },
  236.         ],
  237.       },
  238.       // 上传按钮闸口
  239.       btnLoding: false,
  240.       //  请求头
  241.       headers: { Authorization: "Bearer" + " " + getToken() },
  242.       // 上传地址
  243.       url: process.env.VUE_APP_BASE_API + "/common/uploadWithAbsolutePath",
  244.       // 图片列表
  245.       fileList: [],
  246.     };
  247.   },
  248.   created() {
  249.     this.getList();
  250.   },
  251.   methods: {
  252.     /** 查询preview列表 */
  253.     getList() {
  254.       this.loading = true;
  255.       listPreview(this.queryParams).then((response) => {
  256.         this.previewList = response.rows;
  257.         this.total = response.total;
  258.         this.loading = false;
  259.       });
  260.     },
  261.     // 取消按钮
  262.     cancel() {
  263.       this.open = false;
  264.       this.reset();
  265.     },
  266.     // 表单重置
  267.     reset() {
  268.       this.form = {
  269.         id: null,
  270.         filename: null,
  271.         uploadpath: null,
  272.       };
  273.       this.resetForm("form");
  274.     },
  275.     /** 搜索按钮操作 */
  276.     handleQuery() {
  277.       this.queryParams.pageNum = 1;
  278.       this.getList();
  279.     },
  280.     /** 重置按钮操作 */
  281.     resetQuery() {
  282.       this.resetForm("queryForm");
  283.       this.handleQuery();
  284.     },
  285.     // 多选框选中数据
  286.     handleSelectionChange(selection) {
  287.       this.ids = selection.map((item) => item.id);
  288.       this.single = selection.length !== 1;
  289.       this.multiple = !selection.length;
  290.     },
  291.     /** 新增按钮操作 */
  292.     handleAdd() {
  293.       this.fileRemove();
  294.       this.open = true;
  295.       this.title = "添加文件";
  296.     },
  297.     /** 修改按钮操作 */
  298.     handleUpdate(row) {
  299.       this.reset();
  300.       const id = row.id || this.ids;
  301.       getPreview(id).then((response) => {
  302.         this.form = response.data;
  303.         this.open = true;
  304.         this.title = "修改文件";
  305.       });
  306.     },
  307.     // 预览
  308.     handlePreview(row) {
  309.       let url = row.previewUrl;
  310.       window.open(url);
  311.     },
  312.     // 下载
  313.     handleDownload(row) {
  314.       const baseURL = process.env.VUE_APP_BASE_API
  315.       window.location.href = baseURL + "/common/download/resourceeasy?resource=" + encodeURI(row.uploadpath);
  316.     },
  317.     /** 提交按钮 */
  318.     submitForm() {
  319.       this.$refs["form"].validate((valid) => {
  320.         if (valid) {
  321.           if (this.form.id != null) {
  322.             updatePreview(this.form).then((response) => {
  323.               this.msgSuccess("修改成功");
  324.               this.open = false;
  325.               this.fileList = [];
  326.               this.getList();
  327.             });
  328.           } else {
  329.             addPreview(this.form).then((response) => {
  330.               this.msgSuccess("新增成功");
  331.               this.open = false;
  332.               this.fileList = [];
  333.               this.getList();
  334.             });
  335.           }
  336.         }
  337.       });
  338.     },
  339.     /** 删除按钮操作 */
  340.     handleDelete(row) {
  341.       const ids = row.id || this.ids;
  342.       this.$confirm('是否确认删除文件编号为"' + ids + '"的数据项?', "警告", {
  343.         confirmButtonText: "确定",
  344.         cancelButtonText: "取消",
  345.         type: "warning",
  346.       })
  347.         .then(function () {
  348.           return delPreview(ids);
  349.         })
  350.         .then(() => {
  351.           this.getList();
  352.           this.msgSuccess("删除成功");
  353.         });
  354.     },
  355.     // 文件上传失败
  356.     uploadError(err) {
  357.       this.btnLoding = false;
  358.       this.$message.error(res.msg);
  359.     },
  360.     // 上传中
  361.     uploadProgress(e) {
  362.       this.btnLoding = true;
  363.     },
  364.     // 文件上传之前
  365.     beforeUpload(file) {
  366.       console.log(file, "上传之前");
  367.       const fileName = file.name;
  368.       const fileType = fileName.substring(fileName.lastIndexOf("."));
  369.       if (
  370.         fileType === ".doc" ||
  371.         fileType === ".docx" ||
  372.         fileType === ".xls" ||
  373.         fileType === ".ppt" ||
  374.         fileType === ".pptx" ||
  375.         fileType === ".xlsx"
  376.       ) {
  377.         this.form.filename = file.name;
  378.         // 不处理
  379.       } else {
  380.         this.$message.error("请上传正确的文件类型,.doc,.docx,.xls,.ppt,.xlsx,.pptx,");
  381.         return false;
  382.       }
  383.     },
  384.     // 文件上传成功
  385.     uploadSuccess(res, file, fileList) {
  386.       this.form.uploadpath = res.uploadpath;
  387.       this.btnLoding = false;
  388.       this.fileList = fileList;
  389.       this.$message(res.msg);
  390.     },
  391.     beyond(file, fileList) {
  392.       this.$message({
  393.         message: "最多上传一个文件",
  394.         type: "warning",
  395.       });
  396.     },
  397.     // 移除选择的文件
  398.     fileRemove(file, fileList) {
  399.       this.btnLoding = false;
  400.       this.reset();
  401.       this.fileList = [];
  402.     },
  403.   },
  404. };
  405. </script>

前端js代码

  1. import request from '@/utils/request'
  2. // 查询preview列表
  3. export function listPreview(query) {
  4.   return request({
  5.     url: '/system/preview/list',
  6.     method: 'get',
  7.     params: query
  8.   })
  9. }
  10. // 查询preview详细
  11. export function getPreview(id) {
  12.   return request({
  13.     url: '/system/preview/' + id,
  14.     method: 'get'
  15.   })
  16. }
  17. // 新增preview
  18. export function addPreview(data) {
  19.   return request({
  20.     url: '/system/preview',
  21.     method: 'post',
  22.     data: data
  23.   })
  24. }
  25. // 修改preview
  26. export function updatePreview(data) {
  27.   return request({
  28.     url: '/system/preview',
  29.     method: 'put',
  30.     data: data
  31.   })
  32. }
  33. // 删除preview
  34. export function delPreview(id) {
  35.   return request({
  36.     url: '/system/preview/' + id,
  37.     method: 'delete'
  38.   })
  39. }

后台实体类

  1. package com.ruoyi.system.domain;
  2. import com.ruoyi.common.annotation.Excel;
  3. import com.ruoyi.common.core.domain.BaseEntity;
  4. import org.apache.commons.lang3.builder.ToStringBuilder;
  5. import org.apache.commons.lang3.builder.ToStringStyle;
  6. public class BusFilePreview extends BaseEntity
  7. {
  8.     private static final long serialVersionUID = 1L;
  9.     /** 主键 */
  10.     private Long id;
  11.     /** 原文件名(上传前文件名) */
  12.     @Excel(name = "原文件名", readConverterExp = "上传前文件名")
  13.     private String filename;
  14.     /** 文件后缀(.xls;.xlsx;.ppt;.doc;.docx;.pptx) */
  15.     @Excel(name = "文件后缀", readConverterExp = ".=xls;.xlsx;.ppt;.doc;.docx;.pptx")
  16.     private String filetype;
  17.     /** 上传后文件路径 */
  18.     @Excel(name = "上传后文件路径")
  19.     private String uploadpath;
  20.     /** 上传后文件名 */
  21.     @Excel(name = "上传后文件名")
  22.     private String uploadfilename;
  23.     /** 转换pdf路径 */
  24.     @Excel(name = "转换pdf路径")
  25.     private String pdfpath;
  26.     /** 转换pdf文件名 */
  27.     @Excel(name = "转换pdf文件名")
  28.     private String pdfname;
  29.     /** 预览地址 */
  30.     @Excel(name = "预览地址")
  31.     private String previewUrl;
  32.     public String getPreviewUrl() {
  33.         return previewUrl;
  34.     }
  35.     public void setPreviewUrl(String previewUrl) {
  36.         this.previewUrl = previewUrl;
  37.     }
  38.     public void setId(Long id)
  39.     {
  40.         this.id = id;
  41.     }
  42.     public Long getId()
  43.     {
  44.         return id;
  45.     }
  46.     public void setFilename(String filename)
  47.     {
  48.         this.filename = filename;
  49.     }
  50.     public String getFilename()
  51.     {
  52.         return filename;
  53.     }
  54.     public void setFiletype(String filetype)
  55.     {
  56.         this.filetype = filetype;
  57.     }
  58.     public String getFiletype()
  59.     {
  60.         return filetype;
  61.     }
  62.     public void setUploadpath(String uploadpath)
  63.     {
  64.         this.uploadpath = uploadpath;
  65.     }
  66.     public String getUploadpath()
  67.     {
  68.         return uploadpath;
  69.     }
  70.     public void setUploadfilename(String uploadfilename)
  71.     {
  72.         this.uploadfilename = uploadfilename;
  73.     }
  74.     public String getUploadfilename()
  75.     {
  76.         return uploadfilename;
  77.     }
  78.     public void setPdfpath(String pdfpath)
  79.     {
  80.         this.pdfpath = pdfpath;
  81.     }
  82.     public String getPdfpath()
  83.     {
  84.         return pdfpath;
  85.     }
  86.     public void setPdfname(String pdfname)
  87.     {
  88.         this.pdfname = pdfname;
  89.     }
  90.     public String getPdfname()
  91.     {
  92.         return pdfname;
  93.     }
  94.     @Override
  95.     public String toString() {
  96.         return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
  97.                 .append("id", getId())
  98.                 .append("filename", getFilename())
  99.                 .append("filetype", getFiletype())
  100.                 .append("uploadpath", getUploadpath())
  101.                 .append("uploadfilename", getUploadfilename())
  102.                 .append("pdfpath", getPdfpath())
  103.                 .append("pdfname", getPdfname())
  104.                 .append("createTime", getCreateTime())
  105.                 .append("createBy", getCreateBy())
  106.                 .append("updateTime", getUpdateTime())
  107.                 .append("updateBy", getUpdateBy())
  108.                 .append("remark", getRemark())
  109.                 .toString();
  110.     }
  111. }

后台mapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.ruoyi.system.mapper.BusFilePreviewMapper">
  6.     <resultMap type="BusFilePreview" id="BusFilePreviewResult">
  7.         <result property="id"    column="id"    />
  8.         <result property="filename"    column="fileName"    />
  9.         <result property="filetype"    column="fileType"    />
  10.         <result property="uploadpath"    column="uploadPath"    />
  11.         <result property="uploadfilename"    column="uploadFileName"    />
  12.         <result property="pdfpath"    column="pdfPath"    />
  13.         <result property="pdfname"    column="pdfName"    />
  14.         <result property="createTime"    column="create_time"    />
  15.         <result property="createBy"    column="create_by"    />
  16.         <result property="updateTime"    column="update_time"    />
  17.         <result property="updateBy"    column="update_by"    />
  18.         <result property="remark"    column="remark"    />
  19.         <result property="previewUrl"    column="preview_url"    />
  20.     </resultMap>
  21.     <sql id="selectBusFilePreviewVo">
  22.         select id, fileName, fileType, uploadPath, uploadFileName, pdfPath, pdfName, create_time, create_by, update_time, update_by, remark ,preview_url from bus_file_preview
  23.     </sql>
  24.     <select id="selectBusFilePreviewList" parameterType="BusFilePreview" resultMap="BusFilePreviewResult">
  25.         <include refid="selectBusFilePreviewVo"/>
  26.         <where>
  27.             <if test="filename != null  and filename != ''"> and fileName like concat('%', #{filename}, '%')</if>
  28.             <if test="filetype != null  and filetype != ''"> and fileType = #{filetype}</if>
  29.             <if test="uploadpath != null  and uploadpath != ''"> and uploadPath = #{uploadpath}</if>
  30.             <if test="uploadfilename != null  and uploadfilename != ''"> and uploadFileName like concat('%', #{uploadfilename}, '%')</if>
  31.             <if test="pdfpath != null  and pdfpath != ''"> and pdfPath = #{pdfpath}</if>
  32.             <if test="pdfname != null  and pdfname != ''"> and pdfName like concat('%', #{pdfname}, '%')</if>
  33.         </where>
  34.     </select>
  35.     <select id="selectBusFilePreviewById" parameterType="Long" resultMap="BusFilePreviewResult">
  36.         <include refid="selectBusFilePreviewVo"/>
  37.         where id = #{id}
  38.     </select>
  39.     <insert id="insertBusFilePreview" parameterType="BusFilePreview" useGeneratedKeys="true" keyProperty="id">
  40.         insert into bus_file_preview
  41.         <trim prefix="(" suffix=")" suffixOverrides=",">
  42.             <if test="filename != null">fileName,</if>
  43.             <if test="filetype != null">fileType,</if>
  44.             <if test="uploadpath != null">uploadPath,</if>
  45.             <if test="uploadfilename != null">uploadFileName,</if>
  46.             <if test="pdfpath != null">pdfPath,</if>
  47.             <if test="pdfname != null">pdfName,</if>
  48.             <if test="createTime != null">create_time,</if>
  49.             <if test="createBy != null">create_by,</if>
  50.             <if test="updateTime != null">update_time,</if>
  51.             <if test="updateBy != null">update_by,</if>
  52.             <if test="remark != null">remark,</if>
  53.             <if test="previewUrl != null">preview_url,</if>
  54.          </trim>
  55.         <trim prefix="values (" suffix=")" suffixOverrides=",">
  56.             <if test="filename != null">#{filename},</if>
  57.             <if test="filetype != null">#{filetype},</if>
  58.             <if test="uploadpath != null">#{uploadpath},</if>
  59.             <if test="uploadfilename != null">#{uploadfilename},</if>
  60.             <if test="pdfpath != null">#{pdfpath},</if>
  61.             <if test="pdfname != null">#{pdfname},</if>
  62.             <if test="createTime != null">#{createTime},</if>
  63.             <if test="createBy != null">#{createBy},</if>
  64.             <if test="updateTime != null">#{updateTime},</if>
  65.             <if test="updateBy != null">#{updateBy},</if>
  66.             <if test="remark != null">#{remark},</if>
  67.             <if test="previewUrl != null">#{previewUrl},</if>
  68.          </trim>
  69.     </insert>
  70.     <update id="updateBusFilePreview" parameterType="BusFilePreview">
  71.         update bus_file_preview
  72.         <trim prefix="SET" suffixOverrides=",">
  73.             <if test="filename != null">fileName = #{filename},</if>
  74.             <if test="filetype != null">fileType = #{filetype},</if>
  75.             <if test="uploadpath != null">uploadPath = #{uploadpath},</if>
  76.             <if test="uploadfilename != null">uploadFileName = #{uploadfilename},</if>
  77.             <if test="pdfpath != null">pdfPath = #{pdfpath},</if>
  78.             <if test="pdfname != null">pdfName = #{pdfname},</if>
  79.             <if test="createTime != null">create_time = #{createTime},</if>
  80.             <if test="createBy != null">create_by = #{createBy},</if>
  81.             <if test="updateTime != null">update_time = #{updateTime},</if>
  82.             <if test="updateBy != null">update_by = #{updateBy},</if>
  83.             <if test="remark != null">remark = #{remark},</if>
  84.             <if test="previewUrl != null">preview_url = #{previewUrl},</if>
  85.         </trim>
  86.         where id = #{id}
  87.     </update>
  88.     <delete id="deleteBusFilePreviewById" parameterType="Long">
  89.         delete from bus_file_preview where id = #{id}
  90.     </delete>
  91.     <delete id="deleteBusFilePreviewByIds" parameterType="String">
  92.         delete from bus_file_preview where id in
  93.         <foreach item="id" collection="array" open="(" separator="," close=")">
  94.             #{id}
  95.         </foreach>
  96.     </delete>
  97. </mapper>

后台mapper接口

  1. package com.ruoyi.system.mapper;
  2. import com.ruoyi.system.domain.BusFilePreview;
  3. import java.util.List;
  4. /**
  5.  * previewMapper接口
  6.  *
  7.  * @author ruoyi
  8.  * @date 2021-10-29
  9.  */
  10. public interface BusFilePreviewMapper
  11. {
  12.     /**
  13.      * 查询preview
  14.      *
  15.      * @param id previewID
  16.      * @return preview
  17.      */
  18.     public BusFilePreview selectBusFilePreviewById(Long id);
  19.     /**
  20.      * 查询preview列表
  21.      *
  22.      * @param busFilePreview preview
  23.      * @return preview集合
  24.      */
  25.     public List<BusFilePreview> selectBusFilePreviewList(BusFilePreview busFilePreview);
  26.     /**
  27.      * 新增preview
  28.      *
  29.      * @param busFilePreview preview
  30.      * @return 结果
  31.      */
  32.     public int insertBusFilePreview(BusFilePreview busFilePreview);
  33.     /**
  34.      * 修改preview
  35.      *
  36.      * @param busFilePreview preview
  37.      * @return 结果
  38.      */
  39.     public int updateBusFilePreview(BusFilePreview busFilePreview);
  40.     /**
  41.      * 删除preview
  42.      *
  43.      * @param id previewID
  44.      * @return 结果
  45.      */
  46.     public int deleteBusFilePreviewById(Long id);
  47.     /**
  48.      * 批量删除preview
  49.      *
  50.      * @param ids 需要删除的数据ID
  51.      * @return 结果
  52.      */
  53.     public int deleteBusFilePreviewByIds(Long[] ids);
  54. }

后台service接口

  1. package com.ruoyi.system.service;
  2. import com.ruoyi.system.domain.BusFilePreview;
  3. import java.util.List;
  4. /**
  5.  * previewService接口
  6.  *
  7.  * @author ruoyi
  8.  * @date 2021-10-29
  9.  */
  10. public interface IBusFilePreviewService
  11. {
  12.     /**
  13.      * 查询preview
  14.      *
  15.      * @param id previewID
  16.      * @return preview
  17.      */
  18.     public BusFilePreview selectBusFilePreviewById(Long id);
  19.     /**
  20.      * 查询preview列表
  21.      *
  22.      * @param busFilePreview preview
  23.      * @return preview集合
  24.      */
  25.     public List<BusFilePreview> selectBusFilePreviewList(BusFilePreview busFilePreview);
  26.     /**
  27.      * 新增preview
  28.      *
  29.      * @param busFilePreview preview
  30.      * @return 结果
  31.      */
  32.     public int insertBusFilePreview(BusFilePreview busFilePreview);
  33.     /**
  34.      * 修改preview
  35.      *
  36.      * @param busFilePreview preview
  37.      * @return 结果
  38.      */
  39.     public int updateBusFilePreview(BusFilePreview busFilePreview);
  40.     /**
  41.      * 批量删除preview
  42.      *
  43.      * @param ids 需要删除的previewID
  44.      * @return 结果
  45.      */
  46.     public int deleteBusFilePreviewByIds(Long[] ids);
  47.     /**
  48.      * 删除preview信息
  49.      *
  50.      * @param id previewID
  51.      * @return 结果
  52.      */
  53.     public int deleteBusFilePreviewById(Long id);
  54. }

后台serviceImpl

  1. package com.ruoyi.system.service.impl;
  2. import com.ruoyi.common.utils.DateUtils;
  3. import com.ruoyi.common.utils.SecurityUtils;
  4. import com.ruoyi.system.domain.BusFilePreview;
  5. import com.ruoyi.system.mapper.BusFilePreviewMapper;
  6. import com.ruoyi.system.service.IBusFilePreviewService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import java.util.List;
  10. /**
  11.  * previewService业务层处理
  12.  *
  13.  * @author ruoyi
  14.  * @date 2021-10-29
  15.  */
  16. @Service
  17. public class BusFilePreviewServiceImpl implements IBusFilePreviewService
  18. {
  19.     @Autowired
  20.     private BusFilePreviewMapper busFilePreviewMapper;
  21.     /**
  22.      * 查询preview
  23.      *
  24.      * @param id previewID
  25.      * @return preview
  26.      */
  27.     @Override
  28.     public BusFilePreview selectBusFilePreviewById(Long id)
  29.     {
  30.         return busFilePreviewMapper.selectBusFilePreviewById(id);
  31.     }
  32.     /**
  33.      * 查询preview列表
  34.      *
  35.      * @param busFilePreview preview
  36.      * @return preview
  37.      */
  38.     @Override
  39.     public List<BusFilePreview> selectBusFilePreviewList(BusFilePreview busFilePreview)
  40.     {
  41.         return busFilePreviewMapper.selectBusFilePreviewList(busFilePreview);
  42.     }
  43.     /**
  44.      * 新增preview
  45.      *
  46.      * @param busFilePreview preview
  47.      * @return 结果
  48.      */
  49.     @Override
  50.     public int insertBusFilePreview(BusFilePreview busFilePreview)
  51.     {
  52.         busFilePreview.setCreateTime(DateUtils.getNowDate());
  53.         busFilePreview.setCreateBy(String.valueOf(SecurityUtils.getUsername()));// 创建人
  54.         return busFilePreviewMapper.insertBusFilePreview(busFilePreview);
  55.     }
  56.     /**
  57.      * 修改preview
  58.      *
  59.      * @param busFilePreview preview
  60.      * @return 结果
  61.      */
  62.     @Override
  63.     public int updateBusFilePreview(BusFilePreview busFilePreview)
  64.     {
  65.         busFilePreview.setUpdateTime(DateUtils.getNowDate());
  66.         busFilePreview.setUpdateBy(String.valueOf(SecurityUtils.getUsername()));// 创建人
  67.         return busFilePreviewMapper.updateBusFilePreview(busFilePreview);
  68.     }
  69.     /**
  70.      * 批量删除preview
  71.      *
  72.      * @param ids 需要删除的previewID
  73.      * @return 结果
  74.      */
  75.     @Override
  76.     public int deleteBusFilePreviewByIds(Long[] ids)
  77.     {
  78.         return busFilePreviewMapper.deleteBusFilePreviewByIds(ids);
  79.     }
  80.     /**
  81.      * 删除preview信息
  82.      *
  83.      * @param id previewID
  84.      * @return 结果
  85.      */
  86.     @Override
  87.     public int deleteBusFilePreviewById(Long id)
  88.     {
  89.         return busFilePreviewMapper.deleteBusFilePreviewById(id);
  90.     }
  91. }

后台Controller

  1. package com.ruoyi.web.controller.system;
  2. import com.ruoyi.common.annotation.Log;
  3. import com.ruoyi.common.config.RuoYiConfig;
  4. import com.ruoyi.common.constant.Constants;
  5. import com.ruoyi.common.core.controller.BaseController;
  6. import com.ruoyi.common.core.domain.AjaxResult;
  7. import com.ruoyi.common.core.page.TableDataInfo;
  8. import com.ruoyi.common.enums.BusinessType;
  9. import com.ruoyi.common.utils.StringUtils;
  10. import com.ruoyi.common.utils.pdf.FilePdfUtils;
  11. import com.ruoyi.common.utils.poi.ExcelUtil;
  12. import com.ruoyi.framework.config.ServerConfig;
  13. import com.ruoyi.system.domain.BusFilePreview;
  14. import com.ruoyi.system.service.IBusFilePreviewService;
  15. import io.swagger.annotations.ApiOperation;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.security.access.prepost.PreAuthorize;
  18. import org.springframework.web.bind.annotation.*;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.IOException;
  24. import java.util.List;
  25. /**
  26.  * previewController
  27.  *
  28.  * @author ruoyi
  29.  * @date 2021-10-29
  30.  */
  31. @RestController
  32. @RequestMapping("/system/preview")
  33. public class BusFilePreviewController extends BaseController
  34. {
  35.     @Autowired
  36.     private IBusFilePreviewService busFilePreviewService;
  37.     @Autowired
  38.     private ServerConfig serverConfig;
  39.     /**
  40.      * 查询preview列表
  41.      */
  42.     @GetMapping("/list")
  43.     public TableDataInfo list(BusFilePreview busFilePreview)
  44.     {
  45.         startPage();
  46.         List<BusFilePreview> list = busFilePreviewService.selectBusFilePreviewList(busFilePreview);
  47.         return getDataTable(list);
  48.     }
  49.     /**
  50.      * 获取preview详细信息
  51.      */
  52.     @GetMapping(value = "/{id}")
  53.     public AjaxResult getInfo(@PathVariable("id") Long id)
  54.     {
  55.         return AjaxResult.success(busFilePreviewService.selectBusFilePreviewById(id));
  56.     }
  57.     /**
  58.      * 新增preview
  59.      */
  60.     @Log(title = "preview", businessType = BusinessType.INSERT)
  61.     @PostMapping
  62.     public AjaxResult add(@RequestBody BusFilePreview busFilePreview) throws IOException{
  63.         if (StringUtils.isNull(busFilePreview.getFilename())) {
  64.             AjaxResult.error("缺少文件名称");
  65.         }
  66.         if (StringUtils.isNull(busFilePreview.getUploadpath())) {
  67.             AjaxResult.error("缺少上传文件路径");
  68.         }
  69.         String substringAfter = StringUtils.substringAfter(busFilePreview.getUploadpath(), ".");
  70.         String upName = StringUtils.substringAfterLast(busFilePreview.getUploadpath(), "/");
  71.         busFilePreview.setUploadfilename(upName);
  72.         busFilePreview.setFiletype(substringAfter); //类型
  73.         if ("pdf".equals(substringAfter)){
  74.             FilePdfUtils.copyFile(busFilePreview.getUploadpath(), RuoYiConfig.getProfile());
  75.             String pdfName = StringUtils.substringAfterLast(busFilePreview.getUploadpath(), "/");
  76.             busFilePreview.setPdfpath(RuoYiConfig.getProfile()+ "/" + pdfName);
  77.             busFilePreview.setPdfname(pdfName);
  78.             return  toAjax(busFilePreviewService.insertBusFilePreview(busFilePreview));
  79.         }
  80.         File file = new File(busFilePreview.getUploadpath());
  81.         FileInputStream fileInputStream = new FileInputStream(file);
  82.         String htmFileName = FilePdfUtils.file2pdf(fileInputStream, substringAfter,RuoYiConfig.getProfile());
  83.         String pdfPath = RuoYiConfig.getProfile()+ "/" + htmFileName;
  84.         busFilePreview.setPdfpath(pdfPath);
  85.         String pdfName = StringUtils.substringAfterLast(pdfPath, "/");
  86.         busFilePreview.setPdfname(pdfName);
  87.         String previewUrl = serverConfig.getUrl()+ Constants.RESOURCE_PREFIX+File.separator+htmFileName;
  88.         busFilePreview.setPreviewUrl(previewUrl);
  89.         return toAjax(busFilePreviewService.insertBusFilePreview(busFilePreview));
  90.     }
  91.     /**
  92.      * 修改preview
  93.      */
  94.     @Log(title = "preview", businessType = BusinessType.UPDATE)
  95.     @PutMapping
  96.     public AjaxResult edit(@RequestBody BusFilePreview busFilePreview) throws IOException {
  97.         if (StringUtils.isNull(busFilePreview.getFilename())) {
  98.             AjaxResult.error("缺少文件名称");
  99.         }
  100.         if (StringUtils.isNull(busFilePreview.getUploadpath())) {
  101.             AjaxResult.error("缺少上传文件路径");
  102.         }
  103.         String substringAfter = StringUtils.substringAfter(busFilePreview.getUploadpath(), ".");
  104.         String upName = StringUtils.substringAfterLast(busFilePreview.getUploadpath(), "/");
  105.         busFilePreview.setUploadfilename(upName);
  106.         busFilePreview.setFiletype(substringAfter); //类型
  107.         if ("pdf".equals(substringAfter)){
  108.             FilePdfUtils.copyFile(busFilePreview.getUploadpath(), RuoYiConfig.getProfile());
  109.             String pdfName = StringUtils.substringAfterLast(busFilePreview.getUploadpath(), "/");
  110.             busFilePreview.setPdfpath(RuoYiConfig.getProfile()+ "/" + pdfName);
  111.             busFilePreview.setPdfname(pdfName);
  112.             return  toAjax(busFilePreviewService.insertBusFilePreview(busFilePreview));
  113.         }
  114.         File file = new File(busFilePreview.getUploadpath());
  115.         FileInputStream fileInputStream = new FileInputStream(file);
  116.         String htmFileName = FilePdfUtils.file2pdf(fileInputStream, substringAfter,RuoYiConfig.getProfile());
  117.         String pdfPath = RuoYiConfig.getProfile()+ "/" + htmFileName;
  118.         busFilePreview.setPdfpath(pdfPath);
  119.         String pdfName = StringUtils.substringAfterLast(pdfPath, "/");
  120.         busFilePreview.setPdfname(pdfName);
  121.         String previewUrl = serverConfig.getUrl()+ Constants.RESOURCE_PREFIX+File.separator+htmFileName;
  122.         busFilePreview.setPreviewUrl(previewUrl);
  123.         return toAjax(busFilePreviewService.updateBusFilePreview(busFilePreview));
  124.     }
  125.     /**
  126.      * 删除preview
  127.      */
  128.     @Log(title = "preview", businessType = BusinessType.DELETE)
  129.  @DeleteMapping("/{ids}")
  130.     public AjaxResult remove(@PathVariable Long[] ids)
  131.     {
  132.         return toAjax(busFilePreviewService.deleteBusFilePreviewByIds(ids));
  133.     }
  134.     @GetMapping("/pdf")
  135.     @ApiOperation(value = "预览")
  136.     public void prePDF(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
  137.         BusFilePreview busFilePreview = busFilePreviewService.selectBusFilePreviewById(id);
  138.         if (StringUtils.isNotNull(busFilePreview) && StringUtils.isNotNull(busFilePreview.getPdfpath())) {
  139.             File file = new File(busFilePreview.getPdfpath());
  140.             if (file.exists()) {
  141.                 byte[] data = null;
  142.                 try {
  143.                     FileInputStream input = new FileInputStream(file);
  144.                     data = new byte[input.available()];
  145.                     input.read(data);
  146.                     response.getOutputStream().write(data);
  147.                     input.close();
  148.                 } catch (Exception e) {
  149.                     e.printStackTrace();
  150.                 }
  151.             } else if (!file.exists()){
  152.                 BusFilePreview filePreview = new BusFilePreview();
  153.                 filePreview.setId(id);
  154.                 filePreview.setRemark("文件不存在");
  155.                 busFilePreviewService.updateBusFilePreview(filePreview);
  156.             }
  157.         }
  158.     }
  159. }

后台通用Controller

  1. package com.ruoyi.web.controller.common;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.http.MediaType;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import com.ruoyi.common.config.RuoYiConfig;
  13. import com.ruoyi.common.constant.Constants;
  14. import com.ruoyi.common.core.domain.AjaxResult;
  15. import com.ruoyi.common.utils.StringUtils;
  16. import com.ruoyi.common.utils.file.FileUploadUtils;
  17. import com.ruoyi.common.utils.file.FileUtils;
  18. import com.ruoyi.framework.config.ServerConfig;
  19. import java.io.File;
  20. /**
  21.  * 通用请求处理
  22.  *
  23.  * @author ruoyi
  24.  */
  25. @RestController
  26. public class CommonController
  27. {
  28.     private static final Logger log = LoggerFactory.getLogger(CommonController.class);
  29.     @Autowired
  30.     private ServerConfig serverConfig;
  31.     /**
  32.      * 通用下载请求
  33.      *
  34.      * @param fileName 文件名称
  35.      * @param delete 是否删除
  36.      */
  37.     @GetMapping("common/download")
  38.     public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
  39.     {
  40.         try
  41.         {
  42.             if (!FileUtils.checkAllowDownload(fileName))
  43.             {
  44.                 throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
  45.             }
  46.             String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
  47.             String filePath = RuoYiConfig.getDownloadPath() + fileName;
  48.             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  49.             FileUtils.setAttachmentResponseHeader(response, realFileName);
  50.             FileUtils.writeBytes(filePath, response.getOutputStream());
  51.             if (delete)
  52.             {
  53.                 FileUtils.deleteFile(filePath);
  54.             }
  55.         }
  56.         catch (Exception e)
  57.         {
  58.             log.error("下载文件失败", e);
  59.         }
  60.     }
  61.     /**
  62.      * 通用上传请求
  63.      */
  64.     @PostMapping("/common/upload")
  65.     public AjaxResult uploadFile(MultipartFile file) throws Exception
  66.     {
  67.         try
  68.         {
  69.             // 上传文件路径
  70.             String filePath = RuoYiConfig.getUploadPath();
  71.             // 上传并返回新文件名称
  72.             String fileName = FileUploadUtils.upload(filePath, file);
  73.             String url = serverConfig.getUrl() + fileName;
  74.             AjaxResult ajax = AjaxResult.success();
  75.             ajax.put("fileName", fileName);
  76.             ajax.put("url", url);
  77.             return ajax;
  78.         }
  79.         catch (Exception e)
  80.         {
  81.             return AjaxResult.error(e.getMessage());
  82.         }
  83.     }
  84.     /**
  85.      * 通用上传请求返回磁盘路径
  86.      */
  87.     @PostMapping("/common/uploadWithAbsolutePath")
  88.     public AjaxResult uploadFileWithAbsolutePath(MultipartFile file) throws Exception
  89.     {
  90.         try
  91.         {
  92.             // 上传文件路径
  93.             String filePath = RuoYiConfig.getUploadPath();
  94.             // 上传并返回新文件名称
  95.             String fileName = FileUploadUtils.uploadWithAbsolutePath(filePath, file);
  96.             AjaxResult ajax = AjaxResult.success();
  97.             ajax.put("uploadpath", filePath+ File.separator+fileName);
  98.             return ajax;
  99.         }
  100.         catch (Exception e)
  101.         {
  102.             return AjaxResult.error(e.getMessage());
  103.         }
  104.     }
  105.     /**
  106.      * 本地资源通用下载
  107.      */
  108.     @GetMapping("/common/download/resource")
  109.     public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
  110.             throws Exception
  111.     {
  112.         try
  113.         {
  114.             if (!FileUtils.checkAllowDownload(resource))
  115.             {
  116.                 throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
  117.             }
  118.             // 本地资源路径
  119.             String localPath = RuoYiConfig.getProfile();
  120.             // 数据库资源地址
  121.             String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
  122.             // 下载名称
  123.             String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
  124.             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  125.             FileUtils.setAttachmentResponseHeader(response, downloadName);
  126.             FileUtils.writeBytes(downloadPath, response.getOutputStream());
  127.         }
  128.         catch (Exception e)
  129.         {
  130.             log.error("下载文件失败", e);
  131.         }
  132.     }
  133.     /**
  134.      * 本地资源通用下载
  135.      */
  136.     @GetMapping("/common/download/resourceeasy")
  137.     public void resourceDownloadEasy(String resource, HttpServletRequest request, HttpServletResponse response)
  138.             throws Exception
  139.     {
  140.         try
  141.         {
  142.             if (!FileUtils.checkAllowDownload(resource))
  143.             {
  144.                 throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
  145.             }
  146.             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  147.             FileUtils.setAttachmentResponseHeader(response, resource);
  148.             FileUtils.writeBytes(resource, response.getOutputStream());
  149.         }
  150.         catch (Exception e)
  151.         {
  152.             log.error("下载文件失败", e);
  153.         }
  154.     }
  155. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/628979
推荐阅读
相关标签
  

闽ICP备14008679号