浏览器打开文件
@RequestMapping("/open")
public void openFile(String filePath, HttpServletRequest request, HttpServletResponse response){
File file = new File(filePath);
if (!file.exists()) {
response.setStatus(404);
return;
}
response.setHeader("Cache-Control", "max-age=31556926");
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
response.setHeader("Last-Modified", String.valueOf(file.lastModified()));
response.setContentLength(new Long(file.length()).intValue());
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
response.setContentType(URLConnection.guessContentTypeFromStream(bis));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] bits = new byte[2048];
int len = 0;
while ((len = bis.read(bits)) != -1) {
bos.write(bits, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException ioe) {
}
}
}
浏览器下载文件
@RequestMapping("/download")
public void downloadFile(String filePath, HttpServletRequest request, HttpServletResponse response){
File file = new File(filePath);
if (!file.exists()) {
response.setStatus(404);
return;
}
String fileName = file.getName();
try {
fileName = URLEncoder.encode(fileName,"utf-8");
} catch (UnsupportedEncodingException e) {
}
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Last-Modified", String.valueOf(file.lastModified()));
response.setHeader("ETag", String.valueOf(System.currentTimeMillis()));
response.setContentLength(new Long(file.length()).intValue());
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
response.setContentType(URLConnection.guessContentTypeFromStream(bis));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] bits = new byte[2048];
int len = 0;
while ((len = bis.read(bits)) != -1) {
bos.write(bits, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException ioe) {
}
}