Java中文件下载的代码,记载下来方便使用:
/**
* 下载文件
*/
public void downFile(){
HttpServletResponse response = this.getResponse();
try {
// 清空response
response.reset();
//设置输出的格式
response.setContentType("application/x-download");// 设置为下载application/x-download
response.addHeader("content-type ","application/x-msdownload");
response.setContentType("application/octet-stream");
response.setHeader("content-disposition", "attachment; filename="+ transCharacter(this.getRequest(), "文件名称"));//设定输出文件头
response.addHeader("Content-Length", "1024");
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream("c:/input/a.doc"));
ServletOutputStream toClient = response.getOutputStream();
byte[] buffer = new byte[1024];
int n = 0;
while ((n = fis.read(buffer))!=-1) {
toClient.write(buffer,0,n);
toClient.flush();
}
fis.close();
//输出文件
toClient.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 根据不同的浏览器转字符编码
* @param request
* @param str
* @return
* @throws Exception
*/
private String transCharacter(HttpServletRequest request, String str) throws Exception{
if(request.getHeader("USER-AGENT").toLowerCase().indexOf( "msie" ) > 0){
return URLEncoder.encode(str, "UTF-8");
}else if(request.getHeader("USER-AGENT").toLowerCase().indexOf( "firefox" ) > 0){
return new String(str.getBytes("UTF-8"), "ISO8859-1");
}
return new String(str.getBytes("UTF-8"), "ISO8859-1");
}