springMVC 通過服務器下載功能

通過服務器下載功能

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);
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章