The Java Web file download function is indeed very simple. The following code snippet
String fileName ="....";response.setHeader("Content-disposition","attachment; filename="+fileName);//response.setContentType("application/ms-word");BufferedInputStream bis = null;BufferedOutputStream bos = null; try { bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("" + fileName))); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff,0,bytesRead); } } catch(final IOException e) { System.out.println ( "IOException." + e ); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); }
As shown above, the download function can be completed. However, if we use a Chinese file name, this code will go wrong. There are multiple solutions:
First: Set response. setheader ("content-disposition", "attachment; filename =" + java.net. urlencoder. encode (filename, "UTF-8"); encode the file name in UTF-8 format, so there will be no URL error. In IE6, note that the number of Chinese characters cannot exceed 17.
Second: Set response. setheader ("content-disposition", "attachment; filename =" + new string (filename. getbytes ("gb2312"), "ISO8859-1"); encode the Chinese name as a ISO8859-1. However, this encoding only supports Simplified Chinese.
According to the appeal method, you can combine the two methods to solve most Chinese problems.
Filename = urlencoder. encode (filenamesrc, "UTF-8 ");
If (filename. Length ()> 150) // solves the IE 6.0 bug
Filename = new string (filenamesrc. getbytes ("GBK"), "ISO-8859-1 ");
Response. setheader ("content-disposition", "attachment; filename =" + filename );