本片文章为Java文件下载,仅做以后用到是使用,直接上代码
@RequestMapping(value = "/download")
public void download(HttpServletRequest request,HttpServletResponse resp) {
//获取数据库中的文件路径,具体根据业务需求,例如:WEB-INF/download.xlsx
String urlPath = "数据库的路径或者其他路径";
//获取项目的真实路径,例如:D://project/download/
String realPath = request.getServletContext().getRealPath("/");
//文件真实路径,例如:D://project/download/WEB-INF/download.xlsx
String path = realPath + File.separator + urlPath;
File file = new File(path);
resp.reset();
resp.setContentType("application/octet-stream");
resp.setCharacterEncoding("utf-8");
resp.setContentLength((int) file.length());
//下载到本地的文件名,例如:abc.xlsx(注意:这里跟路径中的文件名区分开)
String downloadName = "你要下载的文件名";
resp.setHeader("Content-Disposition", "attachment;filename=" + downloadName );
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}