vue+axios+springboot文件下載

//前臺代碼
<el-button size="medium" type="primary" @click="downloadFile">Test</el-button>
//js函數
downloadFile(){
      this.axios({
        method: "get",
        url: '/api/downloadFile',
         responseType: 'blob',
        headers: {
          Authorization: localStorage.getItem("token")
        }
      })
        .then(response => {
       //文件名 文件保存對話框中的默認顯示
         let fileName = 'test.txt';
         let data = response.data;
         if(!data){
           return
         }
         console.log(response);
      //構造a標籤 經過a標籤來下載
         let url = window.URL.createObjectURL(new Blob([data]))
         let a = document.createElement('a')
         a.style.display = 'none'
         a.href = url
       //此處的download是a標籤的內容,固定寫法,不是後臺api接口
          a.setAttribute('download',fileName)
         document.body.appendChild(a)
         //點擊下載
         a.click()
         // 下載完成移除元素
         document.body.removeChild(a);
         // 釋放掉blob對象
         window.URL.revokeObjectURL(url);
        })
        .catch(response => {
          this.$message.error(response);
        });
    },

 

//後臺代碼

@RequestMapping(value = "/downLoad", method = RequestMethod.GET)
public static final String downLoad(HttpServletRequest req, HttpServletResponse res){
  Map<String, Object> reMap = new HashMap<>();
  String fileName = "aaa.txt";
  String path = "f:/svss/";
  String filepath = path+fileName;
  OutputStream os = null;
  InputStream is = null;
  try {
    // 清空輸出流
    res.reset();
    res.setCharacterEncoding("utf-8");
    res.setContentType("application/octet-stream");
    res.setHeader("Content-Disposition",
      "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
    // 讀取流
    File f = new File(filepath);
    is = new FileInputStream(f);
    if (is == null) {
      reMap.put("msg", "下載附件失敗");
    }
    ServletOutputStream sout = res.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    bis = new BufferedInputStream(is);
    bos = new BufferedOutputStream(sout);
    byte[] buff = new byte[2048];
    int bytesRead;
    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
      bos.write(buff, 0, bytesRead);
    }
    bos.flush();
    bos.close();
    bis.close();
    is.close();
    os.close();
  } catch (Exception e) {
  reMap.put("msg", "下載附件失敗,error:" + e.getMessage());
  }

  String str = JsonUtil.map2Json(reMap);
  return str;
}ios

相關文章
相關標籤/搜索