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();
        }
    }
相关推荐
皮皮林5519 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
databook12 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar14 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
卡尔特斯14 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
白鲸开源14 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
用户83562907805114 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_14 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
ytadpole14 小时前
Java 25 新特性 更简洁、更高效、更现代
java·后端
纪莫14 小时前
A公司一面:类加载的过程是怎么样的? 双亲委派的优点和缺点? 产生fullGC的情况有哪些? spring的动态代理有哪些?区别是什么? 如何排查CPU使用率过高?
java·java面试⑧股
JavaGuide15 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端