栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring REST-损坏/空白文件正在下载

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring REST-损坏/空白文件正在下载

从服务器下载文件的 方法多种
,可以使用

ResponseEntity<InputStreamResource>
,。
HttpServletResponse
以下是两种下载方法。

@GetMapping("/download1")       public ResponseEntity<InputStreamResource> downloadFile1() throws IOException {          File file = new File(FILE_PATH);          InputStreamResource resource = new InputStreamResource(new FileInputStream(file));          return ResponseEntity.ok()     .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=" + file.getName())     .contentType(MediaType.APPLICATION_PDF).contentLength(file.length())     .body(resource);       }

要么

您可以

StreamingResponseBody
用来下载
文件。在这种情况下,服务器同时将数据写入
OutputStream
浏览器读取的数据,这意味着它是并行的。

@RequestMapping(value = "downloadFile", method = RequestMethod.GET)    public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException {        response.setContentType("application/pdf");        response.setHeader("Content-Disposition", "attachment; filename="demo.pdf"");        InputStream inputStream = new FileInputStream(new File("C:\demo-file.pdf"));        return outputStream -> { int nRead; byte[] data = new byte[1024]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) {     System.out.println("Writing some bytes..");     outputStream.write(data, 0, nRead); }        };    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573380.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号