java返回文件时为图片或pdf等设置在线预览或下载

设置Content-Disposition响应头类型

"inline"查看预览 ; "attachment"下载;

复制代码
inline:表示回复中的消息体会以页面的一部分或者整个页面的形式展示
attchment:以附件形式被下载到本地;
xml 复制代码
/**
 * 文件或图片预览/下载工具类
 * @author zh、
 * @data 2024/1/11 18:35
 */
@Component
@Slf4j
public class FileHttpUtil {

    /**
     * 根据物理路径文件 获取 下载/预览 文件
     * @param file 文件
     * @param type 设置响应头类型 "inline"查看  "attachment"下载
     * @param fileName 文件名 
     * @return 对应类型响应文件
     */
    public static ResponseEntity<?> getResponseEntity(byte[] file , String type , String fileName ){
        ResponseEntity.BodyBuilder responseEntity = ResponseEntity.ok();
        HttpHeaders httpHeaders = new HttpHeaders();
        Tika tika = new Tika();
        String mediaType = tika.detect(file);
        httpHeaders.setContentType(MediaType.parseMediaType(mediaType));
        httpHeaders.setContentDisposition(ContentDisposition.builder(type)
                .filename(URLEncoder.encode(fileName )).build());
        httpHeaders.setCacheControl(CacheControl.noCache());
        //httpHeaders.setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES));
        return responseEntity.headers(httpHeaders).body(file );
    }


需要的pom依赖文件
	<dependency>
      <groupId>org.apache.tika</groupId>
      <artifactId>tika-core</artifactId>
      <version>1.28.4</version>
    </dependency>

接口调用或测试

xml 复制代码
  /**
     * 查询文件
     * @param filePath文件地址 物理路径
     * @param type 设置响应头类型  "inline"查看  "attachment"下载
     * @return 响应文件
     * @throws IOException
     */
    @GetMapping(value = "/file")
    public ResponseEntity<?> file(String filePath,String type){
   		 //根据文件路径去文件服务获取文件
        File file = new File(filePath);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] buf = new byte[fileInputStream.available()];
            fileInputStream.read(buf);
            return FileHttpUtil.getResponseEntity(buf, type,file .getName());
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
相关推荐
Mr数据杨1 小时前
【Codex】用学生入学评估模块建立新生能力画像
android·java·javascript·django·codex·项目开发
2601_962056232 小时前
Spring Boot 入门 与 无法解析符号 springframework 的解决
java·spring boot·后端
Thomas21432 小时前
Java scala 数组 链表
java·链表·scala
威联通网络存储2 小时前
TS-h3087XU-RP 汽车零部件质检追溯部署
python·汽车
亚历克斯神2 小时前
低代码与 AI 的融合趋势——从可视化搭建到自然语言生成应用
java·spring·微服务
你驴我2 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
IT毕设实战小研2 小时前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计
学长毕业设计3 小时前
基于SpringBoot的瑜伽馆网站的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
一嘴一个橘子3 小时前
nginx 常用命令(在 nginx 目录下执行)
java
harmful_sheep3 小时前
java group by常见用法
java·开发语言·python