Springboot流式下载与预览文件

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";
    }
  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中实现视频播放可以通过以下步骤完成: 1. 首先,确保你的Spring Boot项目中已经引入了Web和Thymeleaf依赖。可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2. 创建一个控制器类,用于处理视频请求和传输。在该类上使用`@RestController`注解: ```java @RestController public class VideoController { @RequestMapping(value = "/video", method = RequestMethod.GET, produces = "video/mp4") public ResponseEntity<InputStreamResource> streamVideo() throws IOException { // 通过IO读取视频文件 InputStream videoFileStream = new FileInputStream("path/to/video.mp4"); // 创建传输资源对象 InputStreamResource videoStreamResource = new InputStreamResource(videoFileStream); // 返回响应实体,包含视频和Content-Length头 return ResponseEntity .ok() .contentLength(videoFileStream.available()) .contentType(MediaType.parseMediaType("video/mp4")) .body(videoStreamResource); } } ``` 3. 在上述代码中,需要将`"path/to/video.mp4"`替换为实际视频文件的路径。注意,视频文件必须存在于指定路径。 4. 在Thymeleaf模板中创建一个视频播放页面。创建一个名为`play.html`的文件,并在其中添加以下代码: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Video Player</title> </head> <body> <video width="640" height="480" controls> <source th:src="@{/video}" type="video/mp4"> </video> </body> </html> ``` 5. 启动Spring Boot应用程序,访问`http://localhost:8080/play`即可在浏器中播放视频。 注意:请将视频文件的实际路径替换为你的视频文件路径,并确保视频文件存在。另外,确保视频文件与上述示例代码中指定的Content-Type一致(这里是"video/mp4")。 这样,你就可以在Spring Boot中实现视频播放了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值