【前端】-【前端发送Ajax请求下载文件的方法】-【解决乱码问题】

背景

用户在页面点击导出后,根据用户在页面的输入,提交表单到后端,后端处理好之后调用人力系统的接口查询数据,人力系统将查询结果放在我们的服务器上,我们将该文件下载到用户本地

问题

无任何报错,但是无法下载

原因

ajax方式下载文件时无法触发浏览器打开保存文件对话框,也就无法将下载的文件保存到硬盘上!由于ajax方式请求的数据只能存放在javascript内存空间,可以通过javascript访问,但是无法保存到硬盘,因为javascript不能直接和硬盘交互,否则将是一个安全问题。

代码

前端代码

downloadFile (row) {
    
    
  this.$axios({
    
    
    url: '/help/downloadFile',
    method: 'post',
    responseType: 'blob',// 一定要设置这个,否则会出现乱码
    data: {
    
    
      fileUrl: row.fileUrl,
      fileName: row.fileName
    }
  })
    .then(res => {
    
    
      if (!res.data) {
    
    
        return
      }
      // application/msword 表示要处理为word格式
      // application/vnd.ms-excel 表示要处理excel格式
      let url = window.URL.createObjectURL(new Blob([res.data]),  {
    
     type: 'application/msword;charset=UTF-8' })
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', row.fileName)
      document.body.appendChild(link)
      link.click()
      // 释放URL对象所占资源
      window.URL.revokeObjectURL(url)
      // 用完即删
      document.body.removeChild(link)
    })
    .catch(res => {
    
    })
},

后端代码

@PostMapping("/downloadFile")
public void downloadFile(@Valid @RequestBody FileDownload fileDownload, HttpServletResponse response) throws IOException {
    
    
    if (!fileDownload.getFileUrl().startsWith(FileConstants.RESOURCE_PREFIX)){
    
    
        throw new BaseException("File does not exist");
    }
    String fileUrl = fileDownload.getFileUrl().replace(FileConstants.RESOURCE_PREFIX,FileConstants.PROFILE);
    File file = new File(fileUrl);
    if (!file.exists()){
    
    
        throw new BaseException("File does not exist");
    }
    ServletOutputStream out = null;
   try {
    
    
       byte[] fileArray = FileUtils.readFileToByteArray(file);
       out = response.getOutputStream();
       out.write(fileArray);
   }catch (Exception e){
    
    
        if (out != null){
    
    
            out.close();
        }
   }
}

猜你喜欢

转载自blog.csdn.net/CaraYQ/article/details/130809836