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();
        }
    }
相关推荐
PPPPickup2 分钟前
easychat项目复盘---管理端系统设置
java·开发语言·前端
挖矿大亨7 分钟前
C++中的this指针
java·开发语言·c++
sheji341613 分钟前
【开题答辩全过程】以 共享单车管理系统为例,包含答辩的问题和答案
java
一只小鱼儿吖20 分钟前
从代理ip的底层逻辑探讨下如何选择代理ip商。
网络·python·网络协议·tcp/ip
北北~Simple22 分钟前
接口调不通的情况
java
Kiyra44 分钟前
八股篇(1):LocalThread、CAS和AQS
java·开发语言·spring boot·后端·中间件·性能优化·rocketmq
开心比对错重要1 小时前
进程、线程、虚拟线程详解及线程个数设置
java·jvm·算法·面试
被风吹过的会不会要逝去1 小时前
Java后端开发性能优化排查思路及工具
java·性能优化
程序员阿鹏1 小时前
分布式事务管理
java·开发语言·分布式
山沐与山1 小时前
【设计模式】Python工厂模式与依赖注入:FastAPI的Depends到底在干嘛
python·设计模式·fastapi