---
title: "Sturts2文件下载—中文乱码处理"
author: "demojava"
date: "2010-09-07T15:02:28Z"
tags: []
categories: ["企业架构"]
slug: "sturts2"
draft: false
lastmod: "2012-11-26T09:14:33Z"
id: 757530
url: "https://demojava.iteye.com/blog/757530"
---

//后台处理类

package com.action.action;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.InputStream;  
import java.net.URLDecoder;  
import java.net.URLEncoder;

import com.opensymphony.xwork2.ActionSupport;  
   
public class DownLoadAction extends ActionSupport {    
   
 private static final long serialVersionUID = -2570279127996753260L;

 private String inputPath;    
   
    private String filename;    
   
    public String getInputPath() {    
        return inputPath;    
    }    
   
    public void setInputPath(String inputPath) {    
        this.inputPath = inputPath;    
    }    
   
    public String getFilename() {    
     try {  
            return new String(filename.getBytes(), "ISO-8859-1");  
     } catch (Exception e) {  
           e.printStackTrace();  
           return filename;  
    }

    }    
   
    public void setFilename(String filename) {    
        this.filename =filename;

    }

      
    public InputStream getInputStream() throws Exception {  
      inputPath=URLDecoder.decode(inputPath,"UTF-8");      
   InputStream input=ServletActionContext.getServletContext().getResourceAsStream(inputPath);   //解析服务器资源  
     return input;     
    }    
   
    public String download() throws Exception {    
     System.err.println("错误");  
     try {  
     
  } catch (Exception e) {  
   e.printStackTrace();  
  }  
        return SUCCESS;    
    }    
} 

配置文件：

  &lt;action name="download" class="com.action.action.DownLoadAction"   method="download"&gt;    
            &lt;result name="success" type="stream" &gt;    
                &lt;param name="contentType"&gt;application/octet-stream;charset=ISO8859-1 &lt;/param&gt;    
                &lt;param name="inputName"&gt;inputStream&lt;/param&gt;  
                &lt;param name="bufferSize"&gt;4096&lt;/param&gt;    
                &lt;param name="contentDisposition"&gt;attachment;filename="${filename}"  &lt;/param&gt;  
            &lt;/result&gt;    
        &lt;/action&gt; 

前台页面：

&lt;s:url id="url" action='download' namespace='/struts2' includeParams="none"&gt;  
      &lt;s:param name="inputPath"&gt;/file/utils.rar&lt;/s:param&gt; &lt;s:param name="filename"&gt;utils.rar  
         &lt;/s:param&gt;    
 &lt;/s:url&gt;  
  &lt;s:a href="%{url}"&gt;下载utils.rar&lt;/s:a&gt;     
 //其中"&gt;/file/utils.rar  file为服务器的文件夹

详细参见：[http://www.blogjava.net/xcp/archive/2009/10/30/downloadList.html](http://www.blogjava.net/xcp/archive/2009/10/30/downloadList.html)

附件为上传的demo。