javaWeb页面实现下载

时间:2022-04-22 09:07:04
jsp页面发送请求,后台实现指定路径下的文件,在浏览器上完成下载功能。
@RequestMapping(value = "downloadFile")
public void downloadFile(HttpServletResponse response) throws Exception {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
InputStream is = null;
String zipFileName = "test.zip";
String zipFilePath = "D:\\";
File file = new File(zipFilePath + zipFileName);
try {
is = new FileInputStream(file);
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader(
"Content-disposition",
"attachment; filename="
+ new String(zipFileName.getBytes("GBK"),
"ISO8859-1"));
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
response.setContentType("text/html");
response.getWriter().print("download failed");
} finally {
try {
if (is != null)
is.close();
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}