Tomcat其他位置播放媒体文件servlet

           这个暑假在家搭建服务器,其中遇到了问题:Tomcat放在一个盘,多媒体资源放在另外一个盘。现在要求浏览器能够通过访问servlet访问到多媒体资源。

          一开始我在servlet中直接用io流读文件,然后读多少就发送多少,前端直接访问servlet,视频、音乐能够播放,但是不能拖进。为此,尝试了各种方法,并结合网络资料,花了好几天时间最终实现此功能,部分内容从网上摘取,到底是从哪里找的已经成了迷,特有此篇来记录方法,方便自己和读者以后使用。

          后端代码:


     

     

      //servlet的doGet方法中如下:
      

String path=request.getParameter("path");
        path=URLDecoder.decode(path,"utf-8");
        String ftype=path.substring(path.lastIndexOf("."));
        File f=new File(path);
        String fileName=f.getName();
        System.out.println("path: "+path+"\n"+"fileName: "+fileName);
            FileInputStream fis=new FileInputStream(path);
            ServletOutputStream fos=response.getOutputStream();
            //getBytesFromFile(Fine f)该方法将文件读到内存中,并返回byte[]型对象,Tomcat对JVM的内存大小有设置,如果文件太大,会发生错误。
            byte[] bb=getBytesFromFile(f);
            
            //下面两个头的设置是必须的,此响应头设置文件长度,下面的头设置接收的“类”(ranges是类的意思)。
            //如果缺少这两个头,网页端的播放将会卡顿,而且不能拖进。
            response.setContentLength(bb.length);
            response.setHeader("Accept-Ranges", "bytes");
            byte[] content = new byte[1024];
            BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(bb));
            OutputStream os = response.getOutputStream();
            while (is.read(content) != -1) {
                os.write(content);
            }
            fis.close();

 

private static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            return null;
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length) && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();
        return bytes;
    }

 

前端


前端需要在请求发path——服务器端文件地址。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值