代码语言:javascript复制
public void downloadVideoById(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("下载请求start>>");
String fileName = request.getParameter("fileName");//文件名
String filePath = request.getParameter("filePath");//文件名
try {
if (StringUtil.isEmpty(fileName) || StringUtil.isEmpty(filePath)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print("参数错误,请联系管理员!");
response.flushBuffer();
return;
}
URL pathUrl = new URL(filePath);
HttpURLConnection urlcon = (HttpURLConnection) pathUrl.openConnection();
if(urlcon.getResponseCode()>=400){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print("文件不存在,请联系管理员!");
response.flushBuffer();
return;
}
//获取输入流对象(用于读文件) 网络流
InputStream inputStream = new URL(filePath).openStream();
//本地流文件
// FileInputStream fis = new FileInputStream(new File(filePath));
//动态设置响应类型,根据前台传递文件类型设置响应类型
response.setContentType("application/" fileName.substring(fileName.lastIndexOf(".") 1));
//设置响应头,attachment表示以附件的形式下载,inline表示在线打开
response.setHeader("content-disposition", "attachment;fileName=" URLEncoder.encode(fileName, "UTF-8"));//下载时浏览器显示的名称
//获取输出流对象(用于写文件)
ServletOutputStream os = response.getOutputStream();
//下载文件,使用spring框架中的FileCopyUtils工具
FileCopyUtils.copy(inputStream, os);
} catch (Exception e) {
logger.error("下载失败 start >>",e);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print("下载失败,请联系管理员!");
response.flushBuffer();
}
}
本文由 小马哥 创作,采用 知识共享署名4.0 国际许可协议进行许可 本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名