下载文件

来源:互联网 发布:听打测试软件 编辑:程序博客网 时间:2024/06/07 03:46

public void downFile() throws Exception{//前台调用方法
String type = getParameter("type");//服务器文件名称
String path = ServletActionContext.getServletContext().getRealPath("/resources/"+type+"");
try {
downFile1(path, "");
} catch (IOException e) {
e.printStackTrace();
setAjaxData("0");
}
}


public String downFile(String path, String ContentType)

throws IOException {
if (ContentType == null || ContentType.equals(""))
ContentType = "application/octet-stream";


File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
// String ext = filename.substring(filename.lastIndexOf(".") +
// 1).toUpperCase();
// 获取文件读取刘
InputStream fis = new FileInputStream(path);
// 获取response;
HttpServletResponse response = ServletActionContext.getResponse();
// 响应类型
response.setContentType(ContentType);
// 获取写流
ServletOutputStream os = ServletActionContext.getResponse()
.getOutputStream();
;
// 设置下载文件名
/*
* response.addHeader("Content-Disposition", "attachment;filename=" +
* new String(filename.getBytes()));
*/
response.addHeader("Content-Disposition", "attachment;filename="
+ java.net.URLEncoder.encode(filename, "utf-8"));
// 设置下载文件大小
response.addHeader("Content-Length", "" + file.length());
int i = 0;
byte[] b = new byte[1024 * 8];
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
return null;
}
0 0