博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
图片视频访问servlet(支持苹果视频断点续传)
阅读量:4880 次
发布时间:2019-06-11

本文共 6765 字,大约阅读时间需要 22 分钟。

package com.sm.common.servlet;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.OutputStream;import java.io.RandomAccessFile;import java.io.UnsupportedEncodingException;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.FileCopyUtils;import org.springframework.web.util.UriUtils;import com.sm.common.config.Global;/** * 查看CK上传的图片 * @author ThinkGem * @version 2014-06-25 */public class UserfilesDownloadServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    private Logger logger = LoggerFactory.getLogger(getClass());    public void fileOutputStream(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        String filepath = request.getRequestURI();        int index = filepath.indexOf(Global.USERFILES_BASE_URL);        if (index >= 0) {            filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());        }        try {            filepath = UriUtils.decode(filepath, "UTF-8");        } catch (UnsupportedEncodingException e1) {            logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);        }        File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);        logger.debug("===" + Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath + "===");        RandomAccessFile randomFile = new RandomAccessFile(file, "r");// 只读模式        long contentLength = randomFile.length();        String range = request.getHeader("Range");        int start = 0, end = 0;        if (range != null && range.startsWith("bytes=")) {            String[] values = range.split("=")[1].split("-");            start = Integer.parseInt(values[0]);            if (values.length > 1) {                end = Integer.parseInt(values[1]);            }        }        int requestSize = 0;        if (end != 0 && end > start) {            requestSize = end - start + 1;        } else {            requestSize = Integer.MAX_VALUE;        }        byte[] buffer = new byte[4096];        response.setContentType("video/mp4");        response.setHeader("Accept-Ranges", "bytes");        response.setHeader("ETag", file.getName());        response.setHeader("Last-Modified", new Date().toString());        // 第一次请求只返回content length来让客户端请求多次实际数据        if (range == null) {            response.setHeader("Content-length", contentLength + "");        } else {            // 以后的多次以断点续传的方式来返回视频数据            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);// 206            long requestStart = 0, requestEnd = 0;            String[] ranges = range.split("=");            if (ranges.length > 1) {                String[] rangeDatas = ranges[1].split("-");                requestStart = Integer.parseInt(rangeDatas[0]);                if (rangeDatas.length > 1) {                    requestEnd = Integer.parseInt(rangeDatas[1]);                }            }            long length = 0;            if (requestEnd > 0) {                length = requestEnd - requestStart + 1;                response.setHeader("Content-length", "" + length);                response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);            } else {                length = contentLength - requestStart;                response.setHeader("Content-length", "" + length);                response.setHeader("Content-Range",                        "bytes " + requestStart + "-" + (contentLength - 1) + "/" + contentLength);            }        }        OutputStream out = response.getOutputStream();        try {            int needSize = requestSize;            randomFile.seek(start);            while (needSize > 0) {                int len = randomFile.read(buffer);                if (needSize < buffer.length) {                    out.write(buffer, 0, needSize);                } else {                    out.write(buffer, 0, len);                    if (len < buffer.length) {                        break;                    }                }                needSize -= buffer.length;            }        } catch (FileNotFoundException e) {            request.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));            request.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(request, response);        } catch (Exception e1) {            request.setAttribute("exception", e1);            request.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(request, response);        } finally {            randomFile.close();            out.close();        }    }    public void fileOutputStream2(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        String filepath = req.getRequestURI();        int index = filepath.indexOf(Global.USERFILES_BASE_URL);        if (index >= 0) {            filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());        }        try {            filepath = UriUtils.decode(filepath, "UTF-8");        } catch (UnsupportedEncodingException e1) {            logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);        }        File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);        try {            if (filepath.endsWith(".mp4")) {                resp.setContentType("video/mpeg4; charset=utf-8");                resp.setHeader("Content-disposition", "attachment;filename=" + file.getName());            } else {                resp.setHeader("Content-Type", "application/octet-stream");            }            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());            return;        } catch (FileNotFoundException e) {            req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));            req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);        } catch (Exception e1) {            req.setAttribute("exception", e1);            req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);        }    }    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        fileOutputStream(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        fileOutputStream(req, resp);    }}

 

转载于:https://www.cnblogs.com/fengwenzhee/p/9411371.html

你可能感兴趣的文章
【Android】学习记录<1> -- 初识ffmpeg
查看>>
定位页面元素的位置
查看>>
关于IAsyncResult接口的CompletedSynchronously属性
查看>>
Python:一篇文章掌握Numpy的基本用法
查看>>
序列化与ArrayList 的elementData的修饰关键字transient
查看>>
学习进度17
查看>>
编译原理——算符优先分析文法(附源代码)
查看>>
jboss的启动过程
查看>>
渲染部分
查看>>
力扣——所有可能的路径
查看>>
关于VS项目平台的x86,x64,Any CPU以及Debug和Release的区别
查看>>
解密module_init幕后的故事
查看>>
9个移动网站优化的最佳实践
查看>>
李昌镐:苍老的青春(转载) 韩国围棋职业棋手
查看>>
JPA 使用报Named query not found错误
查看>>
FTP命令使用详解
查看>>
walmart weekly sales
查看>>
面试题07_用两个栈实现队列——剑指offer系列
查看>>
cocos2d-x3.2中加入Android手机震动
查看>>
css3处理sprite背景图压缩来解决H5网页在手机浏览器下图标模糊的问题
查看>>