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();
        }
    }
相关推荐
砍材农夫12 分钟前
spring|spring web|拦截器、过滤器、aop
java·spring boot·spring·spring cloud
vicky05171 小时前
解决 ModuleNotFoundError: No module named ‘torch‘ 笔记
python
wuyk5551 小时前
Python实战项目02:学生成绩管理系统(控制台|CSV导出|完整落地)
开发语言·python
mldong7 小时前
一个 App,十三套后端:手机审批端 uni-jeeflow-app 开源了
java·架构
qq5918406857 小时前
uiautomator2自动化安卓手机操作
python
tqs_123458 小时前
MySQL RR隔离级别死锁|Gap间隙锁、临键锁,订单并发范围查询死锁根因方案
java
80s7778 小时前
动态代理和静态代理的区别,动态代理怎么提高网络安全性
python
逆境不可逃8 小时前
Pi Agent 学习笔记:多个工具怎样并行执行
java
ai小陈9 小时前
CUDA Stream实战:让数据传输与GPU计算真正重叠
人工智能·深度学习·ai·pdf·云计算·gpu算力
Flynt9 小时前
Java 27 升级实测:默认值动得比新特性多,有个老参数会让 JVM 直接起不来
java·jvm·后端