企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
案例代码:https://gitee.com/flymini/codes03/tree/master/learn-bootdown **** **1. 前端** 前端可以采用 ajax 方式提交,或表单方式提交都行。 ```js <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script type="text/javascript"> /** * 提交方式一:采用 ajax 方式提交 */ const downByAjax = () => { axios({ method: 'post', url: 'http://localhost:8080/downFile', params: {'filename': "我的人生.jpeg"}, responseType: 'blob' //响应类型为blob }).then(response => { //从响应头中获取文件名 const filename = window.decodeURI(response.headers['content-disposition']).replace('attachment;filename=', '') //根据二进制对象创造新的链接 const href = URL.createObjectURL(response.data); const a = document.createElement('a'); a.setAttribute('href', href); a.setAttribute('download', filename); a.click(); URL.revokeObjectURL(href); }) } /** * 提交方式二:用表单方式提交 */ const downByForm = () => { //创建表单元素 const form = document.createElement("form"); form.method = "post"; form.action = "http://localhost:8080/downFile"; form.style.display = "none"; //需要携带的参数放在input中 const input = document.createElement("input"); input.name = 'filename'; input.value = '我的人生.jpeg'; form.appendChild(input); document.body.appendChild(form); form.submit(); document.body.removeChild(form); } </script> ``` <br/> **2. 后端** 后端可以返回`void`,或`ResponseEntity`都行。 ```java @RestController public class DownController { /** * 写法一:返回 void */ @PostMapping("/downFile") public void downFile(@RequestParam("filename") String filename, HttpServletResponse response) throws IOException { //防止中文文件名乱码 String exportfileName = URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename=" + exportfileName); response.setHeader("Access-Control-Expose-Headers", "Content-disposition"); response.setCharacterEncoding("utf-8"); //设置文件类型 application/octet-stream response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); //读取文件 byte[] content = Files.readAllBytes(Path.of("f:/app/" + filename)); //将数据写入 HttpServletResponse response.getOutputStream().write(content); } /** * 写法二:返回 ResponseEntity */ @PostMapping("/downFile2") public ResponseEntity<byte[]> downFile2(@RequestParam("filename") String filename) throws IOException { //读取文件 byte[] content = Files.readAllBytes(Path.of("f:/app/" + filename)); //设置HTTP响应头信息 HttpHeaders headers = new HttpHeaders(); //设置文件类型 application/octet-stream headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //防止中文文件名乱码 String exportfileName = URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20"); headers.setContentDispositionFormData("attachment", exportfileName); headers.setContentLength(content.length); headers.add("Access-Control-Expose-Headers", "Content-disposition"); //返回响应实体 return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK); } } ```