springMVC 通过服务器下载功能

来源:互联网 发布:20m网络限速多少合适 编辑:程序博客网 时间:2024/05/17 21:46

通过服务器下载功能

String path = url;
String suffix = path.substring(path.lastIndexOf("."));
StringBuffer buffer = new StringBuffer(显示的name);
buffer.append(suffix);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
       response.setHeader("Content-Disposition", "attachment;fileName="+ new String(buffer.toString().getBytes("gb2312"), "ISO8859-1").toString());
       
       String realPath = request.getSession().getServletContext().getRealPath("/");
String filePath = realPath + path;
File file = new File(filePath); 
Long le = file.length();
response.setContentLength(le.intValue());
InputStream inputStream = null;
OutputStream os = null;
       try {
inputStream=new FileInputStream(file);  
os=response.getOutputStream();  
byte[] b=new byte[1024];  
int length;  
while((length=inputStream.read(b))>0){  
   os.write(b,0,length);  

os.flush();
os.close();
inputStream.close();
} catch (IOException e) {
log.info( "#提醒# 向客户端传输时出现IO异常,但此异常是允许的的,有可能客户端取消了下载,导致此异常,不用关心!" );
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}