欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

代码片段,导出的文件头

程序员文章站 2022-03-22 21:46:54
...
public static void setDownloadHeader(String downloadFileName, HttpServletRequest request,
            HttpServletResponse response, boolean isDirectDownload) {

        try {
            if (PatternUtil.isBlank(downloadFileName)) {
                return;
            }
            String fileType = downloadFileName.substring(downloadFileName.lastIndexOf(".") + 1).toLowerCase();
            response.setCharacterEncoding("UTF-8");
            String userAgent = request.getHeader("User-Agent").toLowerCase();
            if (PatternUtil.isImageFile(downloadFileName) && !isDirectDownload) {
                if (userAgent.indexOf("msie") != -1) {
                    response.setContentType("application/octet-stream");
                } else {
                    response.setContentType("image/" + fileType);
                }
            } else {
                response.setContentType("application/octet-stream");
                if (downloadFileName.length() > 70) {
                    downloadFileName =
                            new StringBuilder().append(downloadFileName.substring(0, 10)).append("....")
                                    .append(fileType).toString();
                }
                if (userAgent.indexOf("firefox") != -1) {
                    response.setHeader("Content-Disposition", new StringBuilder()
                            .append("attachment; filename*=utf8''")
                            .append(URLEncoder.encode(downloadFileName, "UTF-8")).toString());
                } else if (userAgent.indexOf("safari") != -1) {
                    response.setHeader("Content-Disposition", new StringBuilder().append("attachment; filename=")
                            .append(new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1")).toString());
                } else {
                    response.setHeader("Content-Disposition", new StringBuilder().append("attachment; filename=")
                            .append(URLEncoder.encode(downloadFileName, "UTF-8")).toString());
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("set download header error!", e);
        }

    }