springboot實現(xiàn)返回文件流
更新時間:2022年03月18日 09:10:59 作者:han1396735592
這篇文章主要介紹了springboot實現(xiàn)返回文件流方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
springboot返回文件流
@GetMapping(value = "/file/{fileName}") public ResponseEntity<FileSystemResource> getFile(@PathVariable("fileName") String fileName) throws FileNotFoundException { File file = new File(filePath, fileName); if (file.exists()) { return export(file); } System.out.println(file); return null; } public ResponseEntity<FileSystemResource> export(File file) { if (file == null) { return null; } HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", "attachment; filename=" + file.getName()); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("Last-Modified", new Date().toString()); headers.add("ETag", String.valueOf(System.currentTimeMillis())); return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file)); }
springboot返回二進(jìn)制文件流
@GetMapping("/getTemplateFile") @ApiOperation("數(shù)據(jù)模板下載") public ResponseEntity<byte[]> downFile(HttpServletRequest request) throws IOException { File file = new File("C/AA"); filename = getFilename(request, filename); //設(shè)置響應(yīng)頭 HttpHeaders headers = new HttpHeaders(); //通知瀏覽器以下載的方式打開文件 headers.setContentDispositionFormData("attachment", filename); //定義以流的形式下載返回文件數(shù)據(jù) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //使用springmvc框架的ResponseEntity對象封裝返回數(shù)據(jù) return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); } /** * 根據(jù)瀏覽器的不同進(jìn)行編碼設(shè)置 * * @param request 請求對象 * @param filename 需要轉(zhuǎn)碼的文件名 * @return 返回編碼后的文件名 * @throws IOException */ public String getFilename(HttpServletRequest request, String filename) throws IOException { //IE不同版本User-Agent中出現(xiàn)的關(guān)鍵詞 String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"}; //獲取請求頭代理信息 String userAgent = request.getHeader("User-Agent"); for (String keyWord : IEBrowserKeyWords) { if (userAgent.contains(keyWord)) { //IE內(nèi)核瀏覽器,統(tǒng)一為utf-8編碼顯示 return URLEncoder.encode(filename, "UTF-8"); } } //火狐等其他瀏覽器統(tǒng)一為ISO-8859-1編碼顯示 return new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java軟件生產(chǎn)監(jiān)控工具Btrace使用方法詳解
這篇文章主要介紹了Java軟件生產(chǎn)監(jiān)控工具Btrace使用方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07SpringBoot2中使用@RequestHeader獲取請求頭的方法
springMVC/SpringBoot中提供了@RequestHeader注解用來獲取請求頭。本文就詳細(xì)的來介紹一下如何使用,感興趣的可以了解下2021-10-10