关于利用浏览器下载网络视频文件的问题总结

最近由于工作需要,本是做后台的我被迫转到前端设计来,在写相关页面时,遇到一个网络视频下载的问题.

在着手这块时,设想的是从前端发送相关视频的id到后台,然后后台将该视频的URL传到前端,再利用浏览器自带下载工具进行下载.在写代码之前上网查了很多相关资料,都说window.location.href=url,ie和ff浏览器都是可以弹出保存窗口的,但是实际运用却不是这样的,IE是可以弹出窗口进行下载,而ff却不行,它是直接将连接打开播放了..后来网上查了下原因说是火狐在安全性上不支持ActiveX.
就因为这个原因,试了好多种方法都不行,最后只能从后台进行考虑了,利用程序代码弹出浏览器窗口进行保存下载.现贴出相关完整代码,供需用的童鞋们参考下,希望有帮助


页面前端相关代码:

点击此按钮下载,js方法为:

	
window.location='actionDown.do?pid='+id;

后台程序为(springMVC框架下):

// 根据视频id查询下载地址
	@RequestMapping("/Video/actionDown")
	protected String actionDown(
			@RequestParam(value = "pid", required = false) String pid,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		String customerid = (String) session.getAttribute("userId");
		String path = downloadService.downloadpathsearch(pid);
		InputStream input = null;
		OutputStream out = null;
		//String url = null;
		String pathParts=path.substring(path.lastIndexOf("."), path.length());
        String filename = new Date().getTime()+pathParts;
        
        
        HttpURLConnection connnect = null;
        URL url = null;     
        response.reset();
        response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachement;filename="+filename);
        //建立链接
		 try {
			url = new URL(path);
			connnect =  (HttpURLConnection) url.openConnection();
			connnect.connect();
			input= connnect.getInputStream();
			out = new BufferedOutputStream(response.getOutputStream());
			
			byte[] content = new byte[4096];
			int length = -1;
			while ((length = input.read(content)) != -1) {
				out.write(content, 0, length);
			}
			
			// 添加一个下载记录
			downloadService.downloadinsert(pid, customerid);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				input.close();
				connnect.disconnect();
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
       
 
		return null;
	}

此方法,可实现火狐,谷歌,IE等浏览器的下载,需要说明的是IE点击下载的浏览器地址需要服务器的IP地址下载,直接上例子吧
比如上图的下载的浏览器地址是localhost:8080/....IE浏览器是点不开的,换成172.20.220.33:8080/...将localhost换成服务器IP地址是可以下载的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值