问题:后台返回一个stream流,前台无法用blob准确接收,new Blob的字节数和后台返回不一致。
后台返回:

示意代码:
public void downloadTemplate(HttpServletResponse response) {
        String newFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);
        response.setHeader("Custom-Header", newFileName);
        response.setHeader(HttpHeaders.ACCEPT_ENCODING, "UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "Custom-Header");
       
        HttpEntity responseEntity = docService.download();//业务代码获取文件
		OutputStream os = response.getOutputStream();
		responseEntity.writeTo(os);
		os.flush();
		os.close();
}

前端axios代码:是正常可以返回blob数据,并接收

axios.get(api, { responseType: 'blob'}).then((response) => {
         let blob = new Blob([response.data])
         let url = window.URL.createObjectURL(blob);
         let link = document.createElement('a');
        link.href = url;
         link.setAttribute('download', decodeURIComponent(response.headers['custom-header']));   // 给a标签加一个download属性
         link.click();                             //模拟点击
        window.URL.revokeObjectURL(link.href);
     });

前端vue-resource代码:是正常可以返回blob数据,但是接收的数据大小不对

vm.$http.get(url).then(response => {
          const element = document.createElement("a");
          let blob = new Blob([response.data], {'type': 'application/octet-stream;charset=UTF-8'})
          element.href = URL.createObjectURL(blob);
          element.download = decodeURIComponent(response.headers.get("Custom-Header"));
          element.click();
})
改正:vm.$http.get(url,{ responseType: 'blob'}),
一定别忘记设计responseType,返回数据类型为Blob,否则vue-resource默认返回json数据。
Logo

前往低代码交流专区

更多推荐