vue+element+springboot 实现文件下载 超级bug

今天写代码的时候发现一个问题,后台传来的流,前台点击不能下载,查了半天后发现,原来是之前封装的调接口的请求把后台传来的流blob对象字符串化了,所以点击不能下载。所以就重新写了一个原生的请求,就可以下载了

下面附上可以使用的源码:

前端:

axios({
    method: 'get',
    url: this.baseUrl+'/api/upload/downloadFile?fileid='+fileid,
    responseType: 'blob',
    headers:{'token':tokens}
}).then((res) => {
    debugger;
    let data = res.data;
    if(!data){
        return;
    }
    const blob = new Blob([data])
    if (window.navigator.msSaveOrOpenBlob){ // 兼容IE10
        navigator.msSaveBlob(blob,fileName);
    }else { // 其他非IE内核支持H5的浏览器
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click()
    }

}).catch((error)=>{
    this.$message.error(error);
})

 

后端:

/**
 * 下载附件模板
 * @param file
 * @return
 * @throws Exception
 */
@GetMapping("/downloadFile")
public void downloadFile( String fileid,
                     HttpServletRequest request,HttpServletResponse  resp) throws IOException {
    long fileid1 = Long.parseLong(fileid);
    SysUploadfile sysUploadfile = sysUploadFileService.downloadFile(fileid1);
    String fileName = sysUploadfile.getFilename();
    String filePath = sysUploadfile.getBasepath();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(filePath);
        resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Disposition",
                "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        byte[] b = new byte[100];
        int len;
        while ((len = fis.read(b)) > 0) {
            resp.getOutputStream().write(b, 0, len);
        }
    } catch (Exception e) {
        logger.error("文件[ {} ]下载错误", fileName);
    } finally {
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
        fis.close();
    }
}

你可能感兴趣的:(springboot,vue,element)