当前位置: 首页 > 图灵资讯 > 技术篇> 前后端分离下载文件

前后端分离下载文件

来源:图灵教育
时间:2023-06-09 10:10:59

1.前端请求

export function test(params) {  return request({    url: '/test',    method: 'get',    responseType: 'blob',    params: params  })}
2.后端返回
@Override    public void test(HttpServletResponse response) {        try {            response.setContentType("application/msword;charset=utf-8");            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("test.docx", "utf-8"));            ClassLoader classLoader = getClass().getClassLoader();            InputStream inputStream = classLoader.getResourceAsStream("templates/test.docx");                        Map<String, Object> dataModel = new HashMap<>();            dataModel.put("name", "张三");            XWPFTemplate render = XWPFTemplate.compile(inputStream).render(dataModel);                        ServletOutputStream outputStream = response.getOutputStream();            render.write(outputStream);            outputStream.flush();        } catch (Exception e) {            throw new ServiceException(下载异常);        }    }
3.前端处理响应结果
test(){      test().then(res=>{        const blob = new Blob([res]);        const downloadElement = document.createElement("a");        // 创建下载链接        const href = window.URL.createObjectURL(blob);        downloadElement.href = href;        // 文件名下载后        downloadElement.download = "test.docx";        document.body.appendChild(downloadElement);        // 点击下载        downloadElement.click();        document.body.removeChild(downloadElement);        window.URL.revokeObjectURL(href);      })    }