最近由于工作需要,本是做后台的我被迫转到前端设计来,在写相关页面时,遇到一个网络视频下载的问题.
在着手这块时,设想的是从前端发送相关视频的id到后台,然后后台将该视频的URL传到前端,再利用浏览器自带下载工具进行下载.在写代码之前上网查了很多相关资料,都说window.location.href=url,ie和ff浏览器都是可以弹出保存窗口的,但是实际运用却不是这样的,IE是可以弹出窗口进行下载,而ff却不行,它是直接将连接打开播放了..后来网上查了下原因说是火狐在安全性上不支持ActiveX.
就因为这个原因,试了好多种方法都不行,最后只能从后台进行考虑了,利用程序代码弹出浏览器窗口进行保存下载.现贴出相关完整代码,供需用的童鞋们参考下,希望有帮助
后台程序为(springMVC框架下):
此方法,可实现火狐,谷歌,IE等浏览器的下载,需要说明的是IE点击下载的浏览器地址需要服务器的IP地址下载,直接上例子吧
比如上图的下载的浏览器地址是localhost:8080/....IE浏览器是点不开的,换成172.20.220.33:8080/...将localhost换成服务器IP地址是可以下载的
在着手这块时,设想的是从前端发送相关视频的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地址是可以下载的