[フロントエンド]-[フロントエンドが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