`

代码片段,导出的文件头

    博客分类:
  • java
阅读更多
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);
        }

    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics