浏览器下载服务器上jpg等静态资源方法
/**
* 服务器下载静态文件
* @param request
* @param response
* @param filePath
* @param fileName
* @throws Exception
*/
public static void browserDownloadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) throws Exception {
File downloadFile = new File(filePath, fileName);
if (!downloadFile.exists() || !downloadFile.isFile()) {
throw new Exception("文件不存在!");
}
String userAgent = request.getHeader("User-Agent").toLowerCase();
if (userAgent.indexOf("firefox") > -1) { //火狐浏览器
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
response.setHeader("content-disposition", String.format("attachment; filename=\"%s\"", fileName));
} else {
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(downloadFile.getAbsolutePath()); // 获取文件的流
int len = 0;
byte buf[] = new byte[1024];// 缓存作用
out = response.getOutputStream();// 输出流
while ((len = in.read(buf)) > 0) { // 切忌这后面不能加 分号 ”;“
out.write(buf, 0, len);// 向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
}
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}