通过后端接口访问磁盘文件

	/**
	* 加载图片
	*/
    public static void loadImage(HttpServletResponse response,String path) {
        File file = new File("D:\\"+path);
        BufferedInputStream reader = null;
        FileInputStream inputStream = null;
        FileInputStream inp = null;
        try {
            if(file.exists()) {
                ServletOutputStream outw = response.getOutputStream();
                inputStream = new FileInputStream(file);
                inp = new FileInputStream(file);
                int i;
                byte[] buffer = new byte[1024];
                while ((i = inp.read(buffer)) != -1) {
                    outw.write(buffer, 0, i);
                }
                inp.close();
                outw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inp != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

	/**
	* 加载视频
	*/
    public static void playViedo(String url, HttpServletRequest request,
                                 HttpServletResponse response ){
        String filepath = "D:\\" + url;
        RandomAccessFile raf = null;// 负责读取数据
        OutputStream os = null;// 写出数据
        OutputStream out = null;// 缓冲
        try {
            File downloadFile = new File(filepath);
            if (!downloadFile.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            long fileLength = downloadFile.length();// 记录文件大小
            long pastLength = 0;// 记录已下载文件大小
            int rangeSwitch = 0;// 0:从头开始的全文下载;1:从某字节开始的下载(bytes=27000-);2:从某字节开始到某字节结束的下载(bytes=27000-39000)
            long contentLength = 0;// 客户端请求的字节总量
            String rangeBytes = "";// 记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容
            int bsize = 1024;// 缓冲区大小
            byte b[] = new byte[bsize];// 暂存容器

            String range = request.getHeader("Range");
            int responseStatus = 206;
            if (range != null && range.trim().length() > 0 && !"null".equals(range)) {// 客户端请求的下载的文件块的开始字节
                responseStatus = javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT;
//                System.out.println("request.getHeader(\"Range\")=" + range);
                rangeBytes = range.replaceAll("bytes=", "");
                if (rangeBytes.endsWith("-")) {
                    rangeSwitch = 1;
                    rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                    pastLength = Long.parseLong(rangeBytes.trim());
                    contentLength = fileLength - pastLength;
                } else {
                    rangeSwitch = 2;
                    String temp0 = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                    String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length());
                    pastLength = Long.parseLong(temp0.trim());
                }
            } else {
                contentLength = fileLength;// 客户端要求全文下载
            }

            // 清除首部的空白行
            response.reset();
            // 告诉客户端允许断点续传多线程连接下载,响应的格式是:Accept-Ranges: bytes
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Access-Control-Allow-Origin","*");
            // 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1

            if (rangeSwitch != 0) {
                response.setStatus(responseStatus);
                // 不是从最开始下载,断点下载响应号为206
                // 响应的格式是:
                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
                switch (rangeSwitch) {
                    case 1: {
                        String contentRange = new StringBuffer("bytes ")
                                .append(new Long(pastLength).toString()).append("-")
                                .append(new Long(fileLength - 1).toString())
                                .append("/").append(new Long(fileLength).toString())
                                .toString();
                        response.setHeader("Content-Range", contentRange);
                        break;
                    }
                    case 2: {
                        String contentRange = range.replace("=", " ") + "/"
                                + new Long(fileLength).toString();
                        response.setHeader("Content-Range", contentRange);
                        break;
                    }
                    default: {
                        break;
                    }
                }
            } else {
                String contentRange = new StringBuffer("bytes ").append("0-")
                        .append(fileLength - 1).append("/").append(fileLength)
                        .toString();
                response.setHeader("Content-Range", contentRange);
            }
            response.setContentType("video/mp4;charset=UTF-8");
            response.setHeader("Content-Length", String.valueOf(contentLength));
            os = response.getOutputStream();
            out = new BufferedOutputStream(os);
            raf = new RandomAccessFile(downloadFile, "r");
            try {
                long outLength = 0;// 实际输出字节数
                switch (rangeSwitch) {
                    case 0: {
                    }
                    case 1: {
                        raf.seek(pastLength);
                        int n = 0;
                        while ((n = raf.read(b)) != -1) {
                            out.write(b, 0, n);
                            outLength += n;
                        }
                        break;
                    }
                    case 2: {
                        raf.seek(pastLength);
                        int n = 0;
                        long readLength = 0;// 记录已读字节数
                        while (readLength <= contentLength - bsize) {// 大部分字节在这里读取
                            n = raf.read(b);
                            readLength += n;
                            out.write(b, 0, n);
                            outLength += n;
                        }
                        if (readLength <= contentLength) {// 余下的不足 1024 个字节在这里读取
                            n = raf.read(b, 0, (int) (contentLength - readLength));
                            out.write(b, 0, n);
                            outLength += n;
                        }
                        break;
                    }
                    default: {
                        break;
                    }
                }
//                System.out.println("Content-Length为:" + contentLength + ";实际输出字节数:" + outLength);
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值