Web开发下载文件功能(代码如下),文件名如果带有中文,经常会出现乱码现象,需要进行编码。
String fileName = "测试文件.doc";try {
HttpServletResponse response = (HttpServletResponse) FacesContext . getCurrentInstance ().getExternalContext().getResponse();response.setHeader("Content-disposition", "attachment; filename=" + fileName );response.setContentLength((int) file .length());response.setContentType("application/octet-stream;charset=UTF-8");byte[] b = new byte[1024];int i = 0;FileInputStream fis = new FileInputStream( file );ServletOutputStream out = response .getOutputStream();while ((i = fis.read(b)) > 0) {
out.write(b, 0, i);
}out.flush();out.close;fis.close();
} catch (IOException e) {
e.printStackTrace();
}FacesContext.getCurrentInstance().responseComplete();return null ;
方案一:讲文件名编码为Unicode
fileName = URLEncoder.encode(fileName, "UTF-8");
文件名会转换为Unicode编码(
%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.doc
),在IE浏览器下测试正常,但是Firefox浏览器下测试得到的文件名是没有解码的Unicode。
方案二:讲文件名编码为ISO-8859-1
fileName = new String( fileName .getBytes( "UTF-8" ), "ISO-8859-1" );
这种方式在IE下和Firefox下均可以得到中文文件名的文件。但如果文件名中带有空格,Firefox会从空格处截断文件名,需要在编码之前将文件名中的空格替换成下划线之类的可见字符。
fileName = new String( fileName .replace( " " , "_" ).getBytes( "UTF-8" ), "ISO-8859-1" );