JAVA 文件下载乱码问题解决办法

页面设置隐藏的iframe

<iframe id='reqFrame' frameborder='0'  style='display:none' allowtransparency='true' ></iframe>

页面下载按钮

<a  class="easyui-linkbutton" data-options="iconCls:'icon-ok'"  title="/demo/省本部固定资产明细表.xlsx" 
id
="btnDown" href="javascript:void(download('btnDown'))" >下载模板</a>

页面JS脚本

 function download(id){
      $("#reqFrame").attr("src",encodeURI("/servlet/Common?action=downloadByPath&filePath="+$("#"+id).attr("title")));
}

后台servlet方法

public class SV_Common extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public static final Logger logger = Logger.getLogger(SV_Common.class
            .getName());

    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        try {
            if ("downloadByPath".equals(action)) { //下载指定路径的文件
                downloadByPath(request, response);
            } else {
                throw new IllegalArgumentException("没有相匹配的操作类型,请检查opp变量.");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void downloadByPath(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        String filePath = request.getParameter("filePath");
        logger.info("filePath="+filePath);
        String fileFullName = filePath.substring(filePath.lastIndexOf("/") + 1);

        response.reset();
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {  
            logger.info("User-Agent=firefox");
            response.setHeader(
                    "Content-Disposition", 
                    "attachment;filename=" + new String(fileFullName.getBytes("UTF-8"), "ISO8859-1")
                );      
        } else {    
            logger.info("User-Agent=not firefox");
            response.setHeader(
                    "Content-Disposition", 
                    "attachment;filename=" + URLEncoder.encode(fileFullName, "UTF-8")
                );  
        } 
        File file = new File(PathUtil.getPath("") + "/" + filePath);
        response.setContentType(new MimetypesFileTypeMap().getContentType(file));
        
        OutputStream out = response.getOutputStream();
        BufferedInputStream in = null;
        byte[] buffer = new byte[8192];
        int length;
        try
        {    
            in = new BufferedInputStream(
                new FileInputStream(file),8192
            );

            while ( (length = in.read(buffer)) != -1)
            {
                out.write(buffer, 0 ,length);
            }        
        }     
        catch (IOException ex)
        {   
            ex.printStackTrace();
        }
        finally
        {  
            if (out != null)
            {
                try {out.close();}
                catch (IOException ex) {}
                out = null;
            }
            if (in != null)
            {
                try {in.close();}
                catch (IOException ex) {}
                in = null;
            }
        }
        response.flushBuffer(); 
    };
}
原文地址:https://www.cnblogs.com/101key/p/3370622.html