首页 > 代码库 > 解决struts2文件下载中文名问题

解决struts2文件下载中文名问题

package com.bgsnewlook.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.io.InputStream;

import java.net.URLEncoder;


public class Download extends ActionSupport {
    private String inputPath;
    private String contentType;
    private String downFileName;

    public String getInputPath() {
        return inputPath;
    }

    public void setInputPath(String inputPath) throws Exception{

            this.inputPath = new String(inputPath.getBytes("iso-8859-1"), "utf-8");

    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getDownFileName() {
        return downFileName;
    }

    public InputStream getTargetFile()

    {
        return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
    }

    public void setDownFileName(String downFileName) throws Exception  {
//        this.downFileName = downFileName;

            this.downFileName = new String(downFileName.getBytes("iso-8859-1"),"utf-8");
           this.downFileName= URLEncoder.encode(this.downFileName,"utf-8");


}
}

struts配置文件struts.xml

  <action name="download" class="com.bgsnewlook.action.Download" >
            <result type="stream" name="success">
                <param name="contentType">${contentType}</param>

                <param name="inputName">targetFile</param>
                <param name="contentDisposition">
                    filename=${downFileName}
                </param>

            </result>

 

 

---down.jsp

<%@ page contentType="text/html;charset=utf-8" language="java" pageEncoding="utf-8" %>
<html>
<head>
    <title></title>
</head>
<body>
  <a href=http://www.mamicode.com/"download?inputPath=/uploadfiles/1.jpg&contentType=image/jpeg&downFileName=中文">下载文件

</body>
</html>