比如现在在后端生成一个.sql文件并下载到当前浏览器:比如我的后端接口是localhost:8087/user/userController/exportSql,
前端地址是localhost:9095/user#。
一、前端:
<el-button @click="getSql()">导出</el-button> var url = process.env.BASE_API url += '/userController/exportSql?userId=' + userId window.open(url)
注意这里url不能是/user/userController/expoerSql,因为window.open,会把/当成前端的页面地址,而不是后端。
二、后端:
/** * 导出SQL */ @ResponseBody @RequestMapping("/exportSql") public HttpResult exportSql(String userId,HttpServletResponse response){ try { response.reset(); response.setContentType("text/plain"); response.addHeader("Content-Disposition", "attachment;filename=测试user.sql"); BufferedOutputStream buff = null; StringBuffer write = new StringBuffer(); String enter = "\r\n"; ServletOutputStream outSTr = null; try { outSTr = response.getOutputStream(); buff = new BufferedOutputStream(outSTr); //拼接SQL write.append("内容为"+userId); buff.write(write.toString().getBytes("UTF-8")); buff.flush(); buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { buff.close(); outSTr.close(); } catch (Exception e) { e.printStackTrace(); } } return HttpResult.getSuccessInstance(); } catch (Exception e) { logger.error("导出SQL:" + e.getMessage(), e); return HttpResult.getFailedInstance("生成SQL失败"); } } }
如果是视频,修改为:
response.setContentType("video/mpeg4"); response.addHeader("Content-Disposition", "attachment;filename="+ossResourcesInfo.getName());
如果要显示文件大小和预计时长,加上下面这段逻辑
InputStream inputStream = urlConnection.getInputStream(); response.setHeader("Content-Length", ""+contentLength);