@RequestMapping("/downloadBook.do")
@ResponseBody
public void downloadBook(String bookid, HttpServletResponse response,
HttpServletRequest request) {
Book book = this.bookService.getBookByBookid(bookid);
if (book == null) {
return;
}
String bookpath = book.getPath();
int beginIndex = bookpath.lastIndexOf(File.separator);
int endIndex = bookpath.lastIndexOf(".");
String filename = bookpath.substring(beginIndex + 1, endIndex);
// System.out.println(filename);
String suffix = bookpath.substring(endIndex);
if (suffix != null && suffix.length() >= 2) {
suffix = suffix.toLowerCase();
if (suffix.contains("pdf")) {
filename += ".pdf";
} else if (suffix.contains("txt")) {
filename += ".txt";
} else if (suffix.contains("html"))
filename += ".html";
}
try {
filename = URLEncoder.encode(filename, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
log.info("文件名:" + filename);
response.setHeader("Content-Disposition", "attachment;filename="
+ filename);
BufferedInputStream bis = null;
FileInputStream fis = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(bookpath);
bis = new BufferedInputStream(fis);
int length = bis.available();
response.setContentLength(length);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] data = new byte[1024];
while (bis.read(data) != -1) {
bos.write(data);
bos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
// 不要关闭服务器输出,否则可能出错
} catch (IOException e) {
}
}
}
javaweb 结合 springmvc 实现的 文件下载(Maybe myself do like this?)
最新推荐文章于 2023-04-18 17:34:50 发布