我们的框架是JSF 1.1
最近在做下载,文件放到服务器上的某文件夹内,客户端请求后,程序用流的方式读取文件并输出到客户端
需要做到模拟传统JSP那种发送一个URL请求或跳转到该URL,根据传值自动下载但是在实际应用中,发现以下问题:
1)使用一个纯的JSP页面,下载Word、Excel文件乱码,文件名正常;下载txt文件不乱码,但是最上面会多一个空行;
2)写一个JSF的bean绑定到CommandButton上,点击这个Button则下载的文件正确;
3)将该方法写到bean中的Getter方法中,能实现请求该页面就自动下载文件,但是则下载到的文件仍是乱码,而且强制打开Excel文件会发现最后有<html><head>……这样的Html代码
JSF页面调用的方法如下:/**
* <p>
* 功能说明:将服务器上的文件下载到本地 文件名为原文件名
* </p>

* @param strfileName String 处理得到的文件URL+实际文件名
* @param S_Name String  原文件名
* @return void
* @throws IOException
*/
public static void downloadFileAsS_Name(String strfileName,String S_Name) throws IOException {
File exportFile = new File(strfileName);
try {
exportFile = FileEncrypt.dencrypt(exportFile);            //解密
HttpServletResponse httpServletResponse = (HttpServletResponse) 
FacesContext.getCurrentInstance().getExternalContext().getResponse();
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
// 此处只写文件名exportFile.getName(),不需绝对路径

httpServletResponse.setHeader( "Content-Disposition", 
"attachment;filename=" + new String(S_Name.getBytes("gb2312"),"ISO8859-1"));
httpServletResponse.setContentLength((int) exportFile.length());
httpServletResponse.setContentType("application/x-download");

byte[] b = new byte[1024];
int i = 0;
FileInputStream fis = new java.io.FileInputStream(exportFile);
while ((i = fis.read(b)) > 0) {
servletOutputStream.write(b, 0, i);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(e);
throw e;
} catch (Exception e) {
e.printStackTrace();
}
exportFile.delete();
FacesContext.getCurrentInstance().responseComplete();
}将以上代码放入JSP页面,稍作修改:httpServletResponse改为response,该页面也能实现下载但是乱码请各位帮忙分析下
google网上的说法,一般是说页面请求的编码格式、文件类型注册这两种问题,我都避免了
因为JSF手工点击是能够实现下载的

解决方案 »

  1.   

    在 web.xml 里面 加上 下面这段配置代码 试下。 应该 可以<mime-mapping>    
    <extension>doc</extension>   
    <mime-type>application/msword</mime-type>    
    </mime-mapping>  
    <mime-mapping>    
    <extension>xls</extension>    
    <mime-type>application/msexcel</mime-type>     
    </mime-mapping>    
    <mime-mapping>    
    <extension>txt</extension>    
    <mime-type>application/txt</mime-type>    
    </mime-mapping>