java文件下载,实际运用
/**
* 文件下载
*/
@RequestMapping(value = "/downloads", method = RequestMethod.POST)
@Transactional
public void downloads(HttpServletRequest request, HttpServletResponse response) {
//根据实际业务进行修改。
String path = request.getParameter("path") == null ? "" : request.getParameter("path");
String fjmc = request.getParameter("fjmc") == null ? "" : request.getParameter("fjmc");
path = filepath + path;
// path是指欲下载的文件的路径。
File file = new File(path);
// String fileName = request.getParameter("file");
if(file.exists()){
try {
// 取得文件名。
// String filename = file.getName();
//这里是下载以后的文件叫做什么名字。
downfile(fjmc, request, response);
OutputStream out;
FileInputStream inputStream = new FileInputStream(path);
out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
response.setContentType("text/html; charset=UTF-8"); //转码
PrintWriter out = response.getWriter();
out.flush();
out.println("<script defer='defer' type='text/javascript'>");
out.println("alert('文件不存在或已经被删除!');");
// out.println("window.location='/想要跳转的地址';");
out.println("</script>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void downfile(String fileName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
// 判断浏览器,进行不同的加密,这样下载的时候保存的文件名就不会乱码
String userAgent = request.getHeader("User-Agent");
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
response.setContentType("application/octet-stream;charset=utf-8");
response.setCharacterEncoding("UTF-8");
}
亲测项目中可用,如果需要判断文件是否存在,我是在前端另外加了一个判断。