java solve Firefox, Google, IE downloads the file name garbled problem

A. Tools

package com.ahtcm.util;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

public class BrowserEncodeSwitchUtil {

    public static String getContentDisposition(String fileName, HttpServletRequest request) throws UnsupportedEncodingException {
        String content_disposition = "";
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("Safari")) {
            byte[] bytes = fileName.getBytes("UTF-8");
            fileName = new String(bytes, "ISO-8859-1");
            content_disposition = String.format("attachment; filename=\"%s\"", fileName);
        } else {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            content_disposition = "attachment;filename=" + fileName;
        }
        return content_disposition;
    }
}

II. This method is called

@Override
     public  void downloadExcelTpl (Request the HttpServletRequest, HttpServletResponse the Response) { 
        FileInputStream IS = null ;
         the try { 
            String fileName = "resident medical record template import .xls" ; 
            String contentDisposition = BrowserEncodeSwitchUtil.getContentDisposition (fileName, Request); 
            response.setHeader ( "Content -Disposition " , contentDisposition);
             / * get file path * / 
            String realpath = request.getSession () getServletContext () getRealPath (.." / static / import template medical residents .xls " );
            /*读取文件*/
            is=new FileInputStream(realPath);
            IOUtils.copy(is,response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(is !=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 

Guess you like

Origin www.cnblogs.com/wwjj4811/p/12585458.html