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();
        }
    }
相关推荐
程序员张312 分钟前
Maven编译和打包插件
java·spring boot·maven
ybq195133454311 小时前
Redis-主从复制-分布式系统
java·数据库·redis
weixin_472339462 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
小毛驴8502 小时前
Linux 后台启动java jar 程序 nohup java -jar
java·linux·jar
DKPT3 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
Eiceblue4 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
好奇的菜鸟4 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
DuelCode5 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
优创学社25 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理5 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring