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/

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中的内容就是转换出来的内容,具体怎么显示可根据实际情况而定。
结果:
控制台打印

显示

7.blob流方式的.png和.jpg文件
handleImageFilePreview(blob) {
  let url = URL.createObjectURL(blob);
} 
提示:url就是图片地址,可以通过img标签,然后将src的值传入url,就可以查看图片。
结果:

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,以此类推。
结果:

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文件无法预览。
结果:

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
} 
结果:

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);
    }
} 

.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.此种方式预览文件,只能预览浏览器能够支持的文件格式。
结果:

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