struts2下载乱码解决方案

这个下载乱码,困扰了一下午,百度,google了N多方案,都没得,后来一哥们给我试想了一个方案,嘿,对了,于是和大家分享:

 

private String download;
 private Map map=new HashMap();
 
 public Map getMap() {
  return map;
 }

 public void setMap(Map map) {
  this.map = map;
 }

 public String getDownload() {
   return download;
 }
 public void setDownload(String download) {
  this.download = download;
 }

 public InputStream getTargetFile() throws UnsupportedEncodingException{
  String download2=null;
  try {
   download2=new String(download.getBytes("iso8859-1"),"utf-8");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }

//这个流会返回到struts.xml中,不能在编码为utf-8后返回,因为download与struts.xml中的一个ognl对应,所以不能改变它的编码,重新定义一个变量进行接收,然后返回这个变量
  return ServletActionContext.getServletContext().getResourceAsStream("/uploadFile/"+download2);
 }
 
 public String execute(){
  return SUCCESS;
 }
 
 public String  list(){
  String path=ServletActionContext.getRequest().getRealPath("/uploadFile");
  System.out.println(path+"路径");
  listfile(new File(path), map);
  ServletActionContext.getContext().put("map",map);
  
  return "list";
 }

//递归查询所有文件
 public void listfile(File file,Map map){
  if (!file.isFile()) {
   File children[]=file.listFiles();
   for (File f : children) {
    listfile(f, map);
   }
  }else{
   map.put(file.getName(),file.getName());//以存入的名字为key  原始名字为value
   
  }
 }

 

struts.xml中的配置如下:

<constant name="struts.i18n.encoding" value="utf-8" />

 <package name="struts2" extends="struts-default">
  <action name="download" class="cn.download.DownloadAction">
   <!-- 配置fileUpload的拦截器 -->
   <interceptor-ref name="fileUpload">
    <!-- 上传类型的过滤 -->
    <param name="allowedTypes">image/x-png,image/bmp,image/png,image/gif,imagepeg</param>
    <!-- 上传文件大小过滤 -->
    <param name="maximumSize">1024*1024*1</param>
   </interceptor-ref>
   <interceptor-ref name="defaultStack"></interceptor-ref>
   <result name="success" type="stream">
    <param name="contentType">image/jpg</param>
    <param name="inputName">targetFile</param>

<!--download 和action中的属性对应-->
    <param name="contentDisposition">attachment;filename=${download}</param>
    <param name="bufferSize">4096</param>
   </result>
   <result name="list">/index.jsp</result>
  </action>
  <action name="upload" class="cn.upload.UploadAction">
   <result name="success">/result.jsp</result>
   <result name="input">/error.jsp</result>
  </action>
 </package>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值