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


 

posted @ 2020-04-29 17:06  ジ绯色月下ぎ  阅读(1710)  评论(0编辑  收藏  举报