java file download setting Chinese name instance of ES2en.addHeader

  • 2020-12-07 04:02:10
  • OfStack

Examples are as follows:


protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   String browser = "";
   String fileName = " test .txt";
   try {
    browser = request.getHeader("User-Agent");
    if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
     // IE6, IE7  The browser 
     response.addHeader("content-disposition", "attachment;filename="
       + new String(fileName.getBytes(), "ISO8859-1"));
    } else if (-1 < browser.indexOf("MSIE 8.0")) {
     // IE8 
     response.addHeader("content-disposition", "attachment;filename="
       + URLEncoder.encode(fileName, "UTF-8"));
    } else if (-1 < browser.indexOf("MSIE 9.0")) {
     // IE9
     response.addHeader("content-disposition", "attachment;filename="
       + URLEncoder.encode(fileName, "UTF-8"));
    } else if (-1 < browser.indexOf("Chrome")) {
     //  Google 
     response.addHeader("content-disposition",
       "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
    } else if (-1 < browser.indexOf("Safari")) {
     //  apple 
     response.addHeader("content-disposition", "attachment;filename="
       + new String(fileName.getBytes(), "ISO8859-1"));
    } else {
     //  Firefox or any other browser 
     response.addHeader("content-disposition",
       "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
   InputStream in = new FileInputStream("D:\\test.txt");// Gets the file input stream 
    int len = 0;
    byte[] buffer = new byte[1024];
    OutputStream out = response.getOutputStream();
    while ((len = in.read(buffer)) > 0) {
     out.write(buffer,0,len);// Output the buffer data to the client browser 
    }
    in.close();
    out.flush();
    out.close();
 }

Identify each browser, and then decode and code.


Related articles: