Java Web application file download (including Chinese file name garbled processing)

Source: Internet
Author: User
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 );

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.