struts2 解决下载中文名字文件报错问题

idea+Meavn+SSH+tomcat7
public class FileDownloadAction extends ActionSupport{

    private static final long serialVersionUID=1L;
    private String file;
    private String contentType;

    public FileInputStream getDownload() throws FileNotFoundException{
        return new FileInputStream( ServletActionContext.getServletContext().getRealPath("/upload")
                +"/"+file);
    }

    public String getFile() throws UnsupportedOperationException, UnsupportedEncodingException {
        return URLEncoder.encode(file, "utf-8");
    }

    public void setFile(String file) throws UnsupportedEncodingException {
        this.file = new String(file.getBytes("ISO-8859-1"),"utf-8");
    }

    public String getContentType() {
        return ServletActionContext.getServletContext().getMimeType(file);
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }
}

 在 tomcat7 中从get请求获取参数是若包含中文,
 则会发现中文乱码现象
 因为浏览器传送来的数据是以utf-8编码的,在服务器tomcat则以iso-8859-1解码         

<a href="noSimpledownload?file=我真很帅的.txt">我真很帅的.txt</a>
 public void setFile(String file) throws UnsupportedEncodingException {
    this.file = file;
 }
 如果代码这样写,值传进去则会乱码报错。
 应该改成:
 public void setFile(String file) throws UnsupportedEncodingException {
    this.file = new String(file.getBytes("ISO-8859-1"),"utf-8");
 }  
 除了这个还会发现一个问题就是下载的文件名是__.txt,并没有显示中文。
 public String getFile() throws UnsupportedOperationException, UnsupportedEncodingException {
     return URLEncoder.encode(file, "utf-8");
 }
 这样子就可以解决了。
 如果用的是火狐浏览器,依旧是——.txt 我们还需要在struts.xml加入这句;filename*=utf-8''${file}
 <param name="contentDisposition">
     attachment;filename="${file}";filename*=utf-8''${file}
 </param>

参考文章: https://blog.csdn.net/mingxin95/article/details/51765277

猜你喜欢

转载自blog.csdn.net/viscu/article/details/79760035