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