java文件下载文件名中文乱码问题

    /**
     * 文件下载
     *
     * @author lwh
     * @date 2018年6月6日 下午2:03:20
     */
    public void documentDownload() {
        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();
        String documentId = getRequest().getParameter("docId");
        ContractDocument doc = contractDocumentService.getById(Integer.parseInt(documentId));
        try {
            request.setCharacterEncoding("UTF-8");
            String name = doc.getFileName();
            // 设置响应类型
            response.setContentType("application/force-download");
            String path = doc.getFilePath() + File.separator + doc.getFileName();
            InputStream in = new FileInputStream(path);
            String fname = "";
            // 对文件进行url编码
            if (request.getHeader("user-agent").toLowerCase().contains("msie")
                    || request.getHeader("user-agent").toLowerCase().contains("like gecko")// ie10以上取消了msie用户代理字符串
            ) {
                // IE
                fname = URLEncoder.encode(name, "UTF-8");
            } else {
                // 非IE
                fname = new String(name.getBytes("utf-8"), "ISO8859-1");
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fname);
            response.setContentLength(in.available());
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[in.available()];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        }

        catch (IOException ex) {
            ex.printStackTrace();
        }

    }
/**
 * 合同文件
 * 
 * @author lwh
 * @date 2018年6月5日 上午10:11:23
 */
public class ContractDocument extends BaseEntity {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String fileName;// 文件名
    private String filePath;// 文件路径
    private Date uploadtime;// 上传时间
    private User operator;// 操作人
    private User modifier;// 修改人
    private Date modifyTime;// 修改时间
    private Contract contract;// 合同
    private String fileSize;// 文件大小
    private Integer fileType;// 文件类型 0合同文件 1合同附件(预留拓展字段)
    private Integer status;// 状态 0无效 1有效

    /**
     * 文件类型
     * 
     * @author lwh
     * @date 2018年6月5日 上午10:35:33
     */
    
    public  static final class FileType {
        public static final int PRIMARY_FILE = 0;// 合同文件
        public static final int ATTACH_FILE = 1;// 合同附件
    }

    /**
     * 文件状态
     * 
     * @author lwh
     * @date 2018年6月5日 上午10:35:39
     */
    public static final class Status {
        public static final int VALID = 1;// 有效
        public static final int INVALID = 0;// 无效
    }

    // ====================getters and setters=============

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public Date getUploadtime() {
        return uploadtime;
    }

    public void setUploadtime(Date uploadtime) {
        this.uploadtime = uploadtime;
    }

    public User getOperator() {
        return operator;
    }

    public void setOperator(User operator) {
        this.operator = operator;
    }

    public User getModifier() {
        return modifier;
    }

    public void setModifier(User modifier) {
        this.modifier = modifier;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public Contract getContract() {
        return contract;
    }

    public void setContract(Contract contract) {
        this.contract = contract;
    }

    public String getFileSize() {
        return fileSize;
    }

    public void setFileSize(String fileSize) {
        this.fileSize = fileSize;
    }

    public Integer getFileType() {
        return fileType;
    }

    public void setFileType(Integer fileType) {
        this.fileType = fileType;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

}

因为具体业务需求,我每上传一个文件都要将记录持久化到数据库中,文件保存在tomcat下。所有建了一个entity。不用实体的话把第一段代码和ContractDocument有关的去掉,filepath和name填自己的路径就好了。关于下载时候中文名乱码问题的处理,代码如下:注意ie10以上的用户识别字符串已经改为 :User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko  所以不能用ie10一下的判断法则。

      // 对文件进行url编码
            if (request.getHeader("user-agent").toLowerCase().contains("msie")//ie10以
                    || request.getHeader("user-agent").toLowerCase().contains("like gecko")// ie10及以上取消了msie用户代理字符串
            ) {
                // IE
                fname = URLEncoder.encode(name, "UTF-8");
            } else {
                // 非IE
                fname = new String(name.getBytes("utf-8"), "ISO8859-1");
            }

猜你喜欢

转载自www.cnblogs.com/easyunion/p/9145810.html