欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

springboot实现返回文件流

时间:2022-07-06 10:17:18|栏目:JAVA代码|点击:

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返回二进制文件流

    @GetMapping("/getTemplateFile")
    @ApiOperation("数据模板下载")
    public ResponseEntity<byte[]> downFile(HttpServletRequest request) throws IOException {
        File file = new 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.encode(filename, "UTF-8");
            }
        }
        //火狐等其他浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
    }

上一篇:Netty分布式高性能工具类FastThreadLocal和Recycler分析

栏    目:JAVA代码

下一篇:Java文件(io)编程之记事本开发详解

本文标题:springboot实现返回文件流

本文地址:http://www.codeinn.net/misctech/206981.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有