写个通用类
通过response实现下载
这个写有个好处,那就是通用,其他不用spring MVC的也可以用
/**
*
* @param request
* @param response
* @param filePath 文件全路径
* @param contentType (mimeType)默认可传application/octet-stream
* @param realName 下载时显示的文件名
* @throws Exception
*/
public static void download(HttpServletRequest request, HttpServletResponse response, String filePath, String contentType, String realName) throws Exception {
// request.setCharacterEncoding("UTF-8");
// String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileUtil.UPLOADDIR;
if(filePath.indexOf("..")!=-1){
throw new IOException("文件名不合规,含有相对定位符!");
}
long fileLength = new File(filePath).length();
response.setContentType(contentType); // "application/octet-stream"
response.setHeader("Content-disposition", "attachment; filename=" + new String(realName.getBytes("GBK"), "ISO-8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
BufferedOutputStream 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);
}
bis.close();
bos.close();
}