1. 前端导入请求类

 import service from "@/utils/request";

2. 前端编写下载方法

 methods: {
 	/**
     * 下载文件按钮操作
     * @param name 文件名
     */
    handleDownload(name) {
      let filename = name;
      return service
        .post(
          "/monitor/logger/file/download/" + filename,
          {},
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            responseType: "blob",
          }
        )
        .then((data) => {
          let fileReader = new FileReader();
          fileReader.onload = () => {
            try {
              let { code, msg } = JSON.parse(fileReader.result);
              if (code !== 200) this.msgError(msg || "下载失败");
            } catch (err) {
              //console.error(err);
              const content = data;
              const blob = new Blob([content]);
              if ("download" in document.createElement("a")) {
                const elink = document.createElement("a");
                elink.download = filename;
                elink.style.display = "none";
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href);
                document.body.removeChild(elink);
              } else {
                navigator.msSaveBlob(blob, filename);
              }
            }
          };
          fileReader.readAsText(data);
        })
        .catch((r) => {
          console.error(r);
        });
    },
 }

3. 后端方法

 /**
     * 日志文件下载
     * 
     * @param fileName 文件名称
     * @return
     */
    @PreAuthorize("@ss.hasPermi('monitor:logger:file:download')")
    @PostMapping("/file/download/{fileName}")
    public void download(@PathVariable("fileName")String fileName, HttpServletResponse response) throws Exception
    {
        if (StringUtils.isEmpty(fileName))
        {
            throw new Exception("文件名称无效");
        }
        String logPath = getLogPath();
        if (StringUtils.isEmpty(logPath))
        {
            throw new Exception("未找到日志文件目录");
        }
        String filePath = "";
        File directory = new File(logPath);
        List<File> files = (List<File>) FileUtils.listFiles(directory, null, true);
        for (File file : files)
        {
            if (file.getName().equals(fileName) && file.isFile() && file.exists())
            {
                filePath = file.getPath();
                break;
            }
        }
        if (StringUtils.isEmpty(filePath))
        {
            throw new Exception("没有找到文件!");
        }
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.writeBytes(filePath, response.getOutputStream());
    }

返回文件关键部分

response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.writeBytes(filePath, response.getOutputStream());
Logo

快速构建 Web 应用程序

更多推荐