资源下载与统计

如果用servlet返回文件流,用的是机房宽带

ServletOutputStream out = response.getOutputStream();
String filepath = request.getRealPath("/")+"uploadfiles/";
if(null == request.getParameter("sonFilePath")){
System.out.println("无参数");
return;
}
if(null == request.getParameter("fileName")){
System.out.println("无参数");
return;
}

String sonFilePath = new String(request.getParameter("sonFilePath").getBytes("ISO8859_1"),"GB2312").toString();
String filename = new String(request.getParameter("fileName").getBytes("ISO8859_1"),"GB2312").toString();
System.out.println("DownloadFile filepath:" + filepath+sonFilePath);
System.out.println("DownloadFile filename:" + filename);

File file = new File(filepath +sonFilePath+"/"+ filename);
if(!file.exists()){
System.out.println(file.getAbsolutePath()+"文件不存在");
return;
}
//读取文件流
FileInputStream fileInputStream = new FileInputStream(file);
//下载文件
//设置响应头和下载保存的文件名
if(filename != null && filename.length() >0){
// response.setContentType("application/x-msdownload");
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"),"iso8859-1") + "");
response.addHeader("Content-Length", "" + file.length());

if(null != fileInputStream){
int filelen = fileInputStream.available();//filelen/1000k
//文件太大时内存不能一次读出,要循环
byte a[] = new byte[filelen];
fileInputStream.read(a);
out.write(a);
}
fileInputStream.close();
out.close();

}

如果用servlet 统计并跳转到资源地址 可以使用cdn设置好的宽带。减少机房压力。

response.sendRedirect(filePath);

原文地址:https://www.cnblogs.com/sode/p/2860902.html