springboot实现返回文件流

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

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);
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot通过请求对象获取输入流无数据

    目录 请求对象获取输入流无数据问题 方案一:禁用默认的过滤器 方案二:使用@RequestBody注解 方案三:自定义HiddenHttpMethodFilter过滤器 request输入流重复可读 自定义类继承 HttpServletRequestWrapper 定义一个过滤器 Filter 创建过滤器配置类 FilterConfig 请求对象获取输入流无数据问题 昨天下午在开发的时候遇到了奇怪的事情,在SpringBoot的Controller里面直接使用HttpServletRequest

  • Springboot如何通过流返回文件

    目录 如何通过流返回文件 controller类如下 工具类DownLoadUtils如下 以流的方式直接返回 如何通过流返回文件 本人的文件是放在resource/templates目录下,截图如下 controller类如下 @GetMapping(value = "/downfile") public void download(HttpServletResponse response) throws IOException { String fileName = "t

  • springboot如何获取文件流

    目录 springboot获取文件流 前端获取springboot返回的文件流的踩坑 踩过坑的我给您提供一个答案 两种解决方案 springboot获取文件流 在日常开发中,经常会获取项目的相对路径用以获取存放在项目路径下的资源,如获取static/ss.txt 在spring项目中,  可以用request.getRealPath("/")获取项目路径然后拼接起来,再生成流: //拼接地址 String downLoadUrl = request.getRealPath("

  • springboot实现返回文件流

    目录 springboot返回文件流 springboot返回二进制文件流 springboot返回文件流 @GetMapping(value = "/file/{fileName}") public ResponseEntity<FileSystemResource> getFile(@PathVariable("fileName") String fileName) throws FileNotFoundException { File file =

  • vue-cli+axios实现文件上传下载功能(下载接收后台返回文件流)

    vue-cli+axios实现附件上传下载记录: 上传: 这里用formData格式传递参数:请求成功后后台返回上传文件的对应信息. 重点是下载: ############## downloadfile(res) { var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'}); //applicati

  • 利用weixin-java-miniapp生成小程序码并直接返回图片文件流的方法

    有时候我们可能需要在其他的网页上展示我们自己的小程序中某些页面的小程序码,这种时候,我们需要用到小程序的生成小程序码的相关接口. 工具选型 我们仍然选用简单方便的weixin-java-miniapp来完成此功能. 项目配置 详见我们的另一篇文章点此进入 生成小程序码的相关类型 小程序码的其他生成方式以及相关类型在这篇文章点此进入中介绍的较为详细,此处不再赘述,以下仅以生成不限制张数的这种类型来做一个示例. 生成小程序码图片 先获取小程序的service实例wxMaService. 再获取二维码

  • ajax post下载flask文件流以及中文文件名问题

    ajax post下载文件 后端返回文件流,flask中可使用 return send_file(文件路径) 返回二进制文件流,在headers中传送文件相关信息(如文件名). 前端使用 URL.createObjectURL()创建创建一个  DOMString URL对象,创建一个 a 节点,将URL对象赋给a节点的 href 属性,最后调用 click() 方法点击该 a 节点即可弹出浏览器下载框. 展示图片 方法同上,将 a 改成 img , href 改成 src 即可,将URL对象写

  • response文件流输出文件名中文不显示的解决

    目录 文件流输出文件名中文不显示 使用如下方法没有解决 解决方法 response下载时中文文件名乱码 文件流输出文件名中文不显示 response返回文件流 用response.setHeader(“Content-disposition”, “attachment; filename=”+fileName);结果中文名称以“—”下滑下显示. 使用如下方法没有解决 response.setCharacterEncoding("UTF-8"); response.setContentT

  • vue使用axios导出后台返回的文件流为excel表格详解

    目录 使用axios导出后台返回的文件流为excel vue axios导出excel乱码解决 使用axios导出后台返回的文件流为excel 之前有一个需求是要使用post请求,导出后台返回的文件流并在表格中使用,大概思路为使用axios请求回数据,定义数据为blob格式,再创建一个a标签自调就可以完成了 <button @click="download">导出</button> data() {     return {       isClick: tru

  • springboot实现单文件和多文件上传

    本文实例为大家分享了springboot实现单文件/多文件上传的具体代码,供大家参考,具体内容如下 package com.heeexy.example.controller; import com.alibaba.fastjson.JSONObject; import com.heeexy.example.util.CommonUtil; import org.springframework.web.bind.annotation.*; import org.springframework.w

  • SpringBoot下载Excel文件时,报错文件损坏的解决方案

    SpringBoot下载Excel文件文件损坏 我把模板文件放在了resources目录下 maven插件打包项目的时候,默认会压缩resources目录下的文件. 服务器读取的文件流来自于压缩后的文件,而返回给浏览器时,浏览器把他当作正常的文件解析,自然不能得到正确的结果. 解决方案: 配置一下maven插件,打包的时候不要压缩模板文件,排除拓展名为xlsx的文件. <plugin> <groupId>org.apache.maven.plugins</groupId>

随机推荐