直接上代碼java
/**
* @desc 下載已存在的文件
*/
public void sendFile(HttpServletRequest request, HttpServletResponse response, File file, String name) throws IOException {
response.setContentType("application/x-download");
OutputStream output = response.getOutputStream();
String filenamedisplay = name;
response.addHeader("Content-Length",""+file.length());
String userAgent = request.getHeader("User-agent");
byte[] bytes = userAgent.contains("MSIE") ? name.getBytes() : name.getBytes("UTF-8");
filenamedisplay = new String(bytes, "ISO-8859-1");
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filenamedisplay));
int BUFSIZE = 65536;
FileInputStream fis=null;
try{
fis= new FileInputStream(file);
int s;
byte[] buf = new byte[BUFSIZE];
while((s = fis.read(buf))>-1){
output.write(buf, 0, s);
}
}catch (Exception ex) {
ex.printStackTrace();
}finally{
output.flush();
fis.close();
output.close();
}
}