您的位置:首页 > Web前端 > JavaScript

jsf浏览器文件下载的实现及问题!

2012-04-19 10:49 525 查看
经测试IE,chrome,欧鹏等浏览器都可以正常实现文件下载,但是360浏览器下载文件时,当文件太小估计小于6kb时无法正常下载,但文件比较大时就没问题了。

下载代码:

jsf:<h:commandButton value="下载" action="#{userinfoBean.download}"></h:commandButton>

javaBean:

public String download() {

FacesContext ctx = FacesContext.getCurrentInstance();

HttpServletRequest request=(HttpServletRequest)ctx.getExternalContext().getRequest();

String filepath="D://tt.txt";

// String filepath=conn.getfilepath(Integer.parseInt(request.getParameter("fileid")));//"C://Program Files//Apache Software Foundation//Tomcat 5.0//webapps//FileUploadDown//upload//007.txt";

if(!new File(filepath).exists()){

System.out.println("文件不存在...........");

return "";

}

try {

String contentType = "application/octet-stream;charset=iso8859-1";

HttpServletResponse response = (HttpServletResponse) ctx

.getExternalContext().getResponse();

response.setContentType(contentType);

StringBuffer contentDisposition = new StringBuffer();

contentDisposition.append("attachment;");

contentDisposition.append("filename=\"");

contentDisposition.append(new File(filepath).getName());

contentDisposition.append("\"");

//logger.debug(System.getProperty("file.encoding"));

response.setHeader("Content-Disposition", new String( contentDisposition.toString().getBytes(System.getProperty("file.encoding")), "iso8859-1"));

//logger.debug(contentDisposition.toString());

OutputStream out = response.getOutputStream();

byte[] bytes = new byte[1024];

InputStream is = new FileInputStream(filepath);

int b = 0;

while ((b = is.read(bytes, 0, 1024)) > 0) {

out.write(bytes, 0, b);

}

is.close();

out.flush();

ctx.responseComplete();

} catch (Exception e) {

e.printStackTrace();

}

return "";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: