springboot实现返回文件流

网友投稿 1006 2022-08-19


springboot实现返回文件流

目录springboot返回文件流springboot返回二进制文件流

springboot返回文件流

@GetMapping(value = "/file/{fileName}")

public ResponseEntity 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 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 ResponseEntityWyTJjU.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));

}

springboot返回二进制文件流

@GetMapping("/getTemplateFile")

@ApiOperation("数据模板下载")

public ResponseEntity downFile(HttpServletRequest request) throws IOException {

File file = newWyTJjU File("C/AA");

filename = getFilename(request, filename);

//设置响应头

HttpHeaders headers = new HttpHeaders();

//通知浏览器以下载的方式打开文件

headers.setContentDispositionFormData("attachment", filename);

//定义以流的形式下载返回文件数据

headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

//使用springmvc框架的ResponseEntity对象封装返回数据

return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

}

/**

* 根据浏览器的不同进行编码设置

*

* @param request 请求对象

* @param filename 需要转码的文件名

* @return 返回编码后的文件名

* @throws IOException

*/

public String getFilename(HttpServletRequest request, String filename) throws IOException {

//IE不同版本User-Agent中出现的关键词

String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};

//获取请求头代理信息

String userAgent = request.getHeader("User-Agent");

for (String keyWord : IEBrowserKeyWords) {

if (userAgent.contains(keyWord)) {

//IE内核浏览器,统一为utf-8编码显示

return URLEncoder.encodehttp://(filename, "UTF-8");

}

}

//火狐等其他浏览器统一为ISO-8859-1编码显示

return new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:超详细讲解Java秒杀项目用户验证模块的实现
下一篇:SpringBoot通过请求对象获取输入流无数据
相关文章

 发表评论

暂时没有评论,来抢沙发吧~