相关推荐recommended
基于若依前后端分离版(Springboot+Vue)的文件预览
作者:mmseoamin日期:2023-12-21

主要介绍两种方式实现文件预览的方式,一种是通过前端插件匹配不同的文件,另一种就是使用已经完善的文件预览系统。我更推荐使用第二种方式,因为这样会少去很多工作量。本文主要介绍第一种方式,第二种方式会出现在另外一篇文章中。

本文是基于若依前后端分离版本实现文件预览功能。若依官网链接。

通过前端插件匹配文件预览:有两个思路,一个是传blob流,然后将流转成对应的文件格式,再进行预览。另一个是通过后端将文件地址映射出来,然后通过浏览器进行访问。两种方式各有优缺点,blob流方式在进行本地测试阶段,没有发现任何问题,但是当部署到服务器,就会出现文件流传输速度问题,如果是内网使用,速度还可以接收,但是外网使用,预览速度根本无法接收。blob流方式预览就相当于下载完文件后,再进行预览,所以速度很慢。浏览器打开方式只支持浏览器支持预览的文件,很多文件格式不支持。总之,这两种文件预览方式的缺陷还是很大的,如果文件预览支持的格式较少,文件都不是很大,适用于个人学习,只使用电脑端使用而不使用手机端时,可以进行使用。

1.文件操作的时间比简单调用数据库的时间长很多。为了避免前端访问后端接口因为超市而报错,将超时时间设置长一点。将ruoyi-ui/src/utils/request.js文件下的timeout设置为6000000,可以根据自己的使用情况进行设置。

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项,表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 6000000
})

2.文件预览之前,先要进行文件上传。文件上传的内容可以看我写的《SpringBoot实现文件上传和下载》。后端在ruoyi-admin/src/main/resources/application.yml文件最后面添加文件路径配置,文件地址可以自行设置。

prop:
	filePath: d:/csdn/onlineFile/

基于若依前后端分离版(Springboot+Vue)的文件预览,第1张

3.后端返回文件流的接口,其中filePath是在controller类中通过@Value导入。

    @Value("${prop.filePath}")
    private String filePath;
/**
     * 根据文件名下载文件
     *
     * @param fileName 文件名,是由文件id+文件扩展名(extName)组成
     * @return 文件信息
     * @throws IOException
     */
@GetMapping("/download")
public ResponseEntity download(String fileName) throws IOException {
    String path = filePath + fileName;
    FileSystemResource file = new FileSystemResource(path);
    // 设置响应头
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
    return ResponseEntity
    .ok()
    .headers(headers)
    .contentLength(file.contentLength())
    .contentType(MediaType.parseMediaType("application/octet-stream"))
    .body(new InputStreamResource(file.getInputStream()));
}

4.在ruoyi-ui/src/api下面创建文件夹file,在此文件夹下创建file.js文件,用于访问与文件有关的后端接口。

import request from "@/utils/request";
let fileUrl = '后端controller的RequestMapping的值'
export function getPrevieweFile(fileName) {
  return request({
    url: fileUrl + '/download',
    method: 'get',
    params: {
      fileName
    },
    responseType: 'blob'
  })
}

注意:

1.url为后端controller的RequestMapping的值+RequestMapping的值。

2.返回类型必须设置为blob。

5.blob值的获取方式

getPrevieweFile(fileName).then(res => {
  let blob = new Blob([res]);
  //通过switch,调用不同类型文件的处理函数
  switch (file.extName) {
    case '.txt':
      this.previewData.type = 'txt';
      this.handleTxtFilePreview(blob);
      break;
    case '.png':
      this.previewData.type = 'image';
      this.handleImageFilePreview(blob);
      break;
    case '.jpg':
      this.previewData.type = 'image';
      this.handleImageFilePreview(blob);
      break;
    case '.xls':
      this.previewData.type = 'excel';
      this.handleExcelFilePreview(blob);
      break;
    case '.xlsx':
      this.previewData.type = 'excel';
      this.handleExcelFilePreview(blob);
      break;
    case '.docx':
      this.previewData.type = 'word';
      this.handleWrodFilePreview(blob);
      break;
    case '.pdf':
      this.previewData.type = 'pdf';
      this.handlePdfFilePreview(blob);
      break;
  }
})

6.blob流方式的.txt文件

handleTxtFilePreview(blob) {
  let reader = new FileReader();
  reader.readAsArrayBuffer(blob);
  reader.onload = (evt) => {
    let ints = new Uint8Array(evt.target.result); //要使用读取的内容,所以将读取内容转化成Uint8Array
    ints = ints.slice(0, blob.size); //截取一段读取的内容
    let text = new TextDecoder('utf-8').decode(ints); //二进制缓存区内容转化成中文(即也就是读取到的内容)
    console.log(text);
  };
}

提示:text中的内容就是转换出来的内容,具体怎么显示可根据实际情况而定。

结果:

控制台打印

基于若依前后端分离版(Springboot+Vue)的文件预览,第2张

显示

基于若依前后端分离版(Springboot+Vue)的文件预览,第3张

7.blob流方式的.png和.jpg文件

handleImageFilePreview(blob) {
  let url = URL.createObjectURL(blob);
}

提示:url就是图片地址,可以通过img标签,然后将src的值传入url,就可以查看图片。

结果:

基于若依前后端分离版(Springboot+Vue)的文件预览,第4张

8.blob流方式的.xls和.xlsx文件

handleExcelFilePreview(blob) {
  let reader = new FileReader();
  reader.readAsArrayBuffer(blob);
  reader.onload = (evt) => {
    let ints = new Uint8Array(evt.target.result); //要使用读取的内容,所以将读取内容转化成Uint8Array
    ints = ints.slice(0, blob.size);
    let workBook = xlsx.read(ints, { type: "array" });
    let sheetNames = workBook.SheetNames;
    let sheetName = sheetNames[0];
    let workSheet = workBook.Sheets[sheetName];
    //获取Excle内容,并将空内容用空值保存
    let excelTable = xlsx.utils.sheet_to_json(workSheet, { defval: '' });
    // 获取Excel头部
    let tableThead = Array.from(Object.keys(excelTable[0])).map(
      (item) => {
        return item
      }
    );
    this.previewData.content = {};
    this.previewData.content.tableContent = excelTable;
    this.previewData.content.tableThead = tableThead;
    this.previewDialogOpen = true;
  }
}

注意:

1.vue需要安装插件xlsx。安装方式:npm install xlsx

2.引入方式:import * as xlsx from "xlsx"

3.当前只考虑excel只有一个sheet的情况,如果excel有多个,可以递归sheetNames,然后读出所有数据,再进行显示。sheetNames[0]代表第一个sheet,以此类推。

结果:

基于若依前后端分离版(Springboot+Vue)的文件预览,第5张

9.blob流方式的.docx文件

handleWrodFilePreview(blob) {
  this.previewDialogOpen = true;
  let docx = require("docx-preview");
  this.$nextTick(() => {
    docx.renderAsync(blob, this.$refs.word);
  })
}
 

注意:

1.vue需要安装插件docx-preview。安装方式:npm install docx-preview

2.只能预览.docx文件,.doc文件无法预览。

结果:

基于若依前后端分离版(Springboot+Vue)的文件预览,第6张

10.blob流方式的.pdf文件

handlePdfFilePreview(blob) {
  this.previewData.src = URL.createObjectURL(blob);
  let loadingTask = pdf.createLoadingTask(this.previewData.src);
  loadingTask.promise.then((pdf) => {
    this.previewData.pdfPages = pdf.numPages;
  })
}

注意:

1.vue需要安装插件vue-pdf。安装方式:npm install vue-pdf

2.引入方式:import pdf from "vue-pdf"

3.components注入方式:

4.如果pdf文件过大,会导致浏览器崩溃。

components: {
  pdf
}

结果:

基于若依前后端分离版(Springboot+Vue)的文件预览,第7张

11.进行下面文件预览之前,先将文件地址映射出来。在ruoyi-admin/src/main/com.ruoyi包下,创建包config,然后在config包下创建MyWebMvcConfig配置类,将文件地址映射出来。由于使用若依系统,为了测试方便,将映射地址权限设置为任何情况下都可以访问。具体方法,打开ruoyi-framework/src/main/java/com.ruoyi.framework/config/SecurityConfig.class,在静态资源下面添加文件映射地址的访问权限为任何人可以访问。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Value("${prop.filePath}")
    private String filePath;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 匹配到resourceHandler,将URL映射至location,也就是本地文件夹
        registry.addResourceHandler("/data/webFiles/**").addResourceLocations("file:" + filePath);
    }
}

基于若依前后端分离版(Springboot+Vue)的文件预览,第8张

.antMatchers("/data/webFiles/**").permitAll()

注意:

1.文件预览方式是后端ip(localhost) + : + 后端端口号(8111) + 文件映射地址(/data/webFile/) + 文件名(48576e3f96d5433bbd35f7cf16b952a6.pdf)。使用默认方式的地址为http://localhost:8111/data/webFiles/48576e3f96d5433bbd35f7cf16b952a6.pdf

2.以上面文件映射地址为例,/data/webFile/的作用相当于文件路径d:/csdn/onlineFile/。如果在d:/csdn/onlineFile的文件夹下,有个test文件夹对应文件路径为d:/csdn/onlineFile/test/,那么访问此文件夹下的文件,地址访问路径就会变成http://localhost:8111/data/webFiles/test/ + 文件名。

3.此种方式预览文件,只能预览浏览器能够支持的文件格式。

结果:

基于若依前后端分离版(Springboot+Vue)的文件预览,第9张

文章开始提到的另外一种方式就是通过kkfileview实现文件预览,这种方式能够快速搭建文件系统,支持多种格式的预览功能,预览速度快,可以作为一个独立的系统使用,不影响主系统架构,不受浏览器、电脑端或手机端的影响。

后面文章会有专门讲解kkfileview如何配置和打包使用。

文章链接:

支持外网访问的kkfileview文件预览系统的详细使用过程

我也是个新手,上面很多内容不够完善,甚至有些是错误的,请大家见谅。这是我在学习过程中做的笔记,感觉对大家可能有所帮助才发出来的,大家可以选择性查看。我也是在不断学习,不断完善自己。如果我在学习过程中,感觉对大家有用的部分,也会再次分享给大家的。谢谢!