Springboot流式下载与预览文件

本文介绍了如何使用Springboot实现流式文件下载,包括附件下载和内嵌预览,并展示了如何根据文件类型设置Content-Disposition和Content-Type。同时,通过示例代码展示了如何处理不同文件类型和使用getContentType方法来确定内容类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot流式下载与预览文件

1.流式下载

 	@RequestMapping(value = "/precede", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> Test02(String path) throws Exception {
        //下面两行,初始化hdfs配置连接
        ResponseEntity<InputStreamResource> result = filebiz.preFile(path);
        return result;
    }
public  ResponseEntity<InputStreamResource> preFile( String path) throws Exception {
        configuration=new Configuration();
        fileSystem=FileSystem.get(new URI(HDFS_PATH),configuration,username);
        FSDataInputStream in = fileSystem.open(new Path(path));
        String fileName=path.substring(path.lastIndexOf("/")+1);
    //不管是哪种的类型的文件读取只要拿到流就行
        try {
            byte[] testBytes = new byte[in.available()];
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Content-Language", "UTF-8");
            //最终这句,让文件内容以流的形式输出
            return ResponseEntity.ok().headers(headers).contentLength(testBytes.length)
                    .contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(in));
        } catch (IOException e) {
            log.info("downfile is error" + e.getMessage());
        }finally {

        }
        log.info("file is null" + fileName);
        return null;
    }

重点:

//设置以附件类型下载:attachment 
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
 //设置以 application/octet-stream: 未知类型 当然你也可以设置为具体类型
 ResponseEntity.ok().headers(headers).contentLength(testBytes.length)
                    .contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(in));

1.流式预览文件(txt和图片)

public  ResponseEntity<InputStreamResource> preFile( String path) throws Exception {
        configuration=new Configuration();
        fileSystem=FileSystem.get(new URI(HDFS_PATH),configuration,username);
        FSDataInputStream in = fileSystem.open(new Path(path));
        String fileName=path.substring(path.lastIndexOf("/")+1);
    //不管是哪种的类型的文件读取只要拿到流就行
        try {
            byte[] testBytes = new byte[in.available()];
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("inline; filename=\"%s\"", fileName));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Content-Language", "UTF-8");
            //最终这句,让文件内容以流的形式输出 必须给定文件类型!
            return ResponseEntity.ok().headers(headers).contentLength(testBytes.length)
                    .contentType(MediaType.parseMediaType(getContentType(path))).body(new InputStreamResource(in));
        } catch (IOException e) {
            log.info("downfile is error" + e.getMessage());
        }finally {

        }
        log.info("file is null" + fileName);
        return null;
    }

重点:

 //设置为inline 内嵌显示一个文件,被支持的文件类型就会直接打开,比如txt和图片
 headers.add("Content-Disposition", String.format("inline; filename=\"%s\"", fileName));
//必须设置为具体文件类型
return ResponseEntity.ok().headers(headers).contentLength(testBytes.length)
                    .contentType(MediaType.parseMediaType(getContentType(path))).body(new InputStreamResource(in));
简单判断文件类型:
 public static  String getContentType(String fileName){
        //文件名后缀
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if(".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if(".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)  || ".png".equalsIgnoreCase(fileExtension) ){
            return "image/jpeg";
        }
        if(".html".equalsIgnoreCase(fileExtension)){
            return "text/html";
        }
        if(".txt".equalsIgnoreCase(fileExtension)){
            return "text/plain";
        }
        if(".vsd".equalsIgnoreCase(fileExtension)){
            return "application/vnd.visio";
        }
        if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if(".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if(".doc".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if(".docx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }
        if(".pdf".equalsIgnoreCase(fileExtension)) {
            return "application/pdf";
        }
        return "application/octet-stream";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值