struts2文件下载,动态设置资源地址

转自:http://blog.csdn.net/ctrl_shift_del/article/details/6277340

 

 1 ServletActionContext.getServletContext().getResourceAsStream("/"+tempfile); 

这是java加载资源的方法,所谓资源,实际上是任何一个文件,但特别的 是,getResourceAsStream这个方法不使用绝对路径,
而是使用相对于classpath环境变量的相对路径。

所 以,如果写:
 1 getResourceAsStream("/resource.xml"); 

则要保证classpath下有 resource.xml文件就能找到。

通常,开发环境下,src目录(也就是源代码所在的目录)是包含在classpath中的,
而 在tomcat下,classpath其一指向:WEB-INF/classes目录。

 

另:如需使用绝对路径则可使用方法:

1 public InputStream getVoiceFile() throws FileNotFoundException {
2            return new FileInputStream("D:/test.wav");
3    }

 

 

下面看一个完整的项目相关代码(struts2应用):

action 中的java 部分代码:

 1 public InputStream getVoiceFile() throws FileNotFoundException {
 2 
 3 
 4            return new FileInputStream(this.getCurrentFileFullName());
 5 
 6               //return ServletActionContext.getServletContext().getResourceAsStream(this.getCurrentFileFullName());
 7       }
 8 
 9     public String voice(){
10             return "voice";
11       }
12 
13 }

 

 

struts.xml中部分代码:

 

1 <result name="voice" type="stream">
2                 <!-- 下载文件类型 -->
3                 <param name="contentType">audio/wav</param>
4                 <param name="inputName">inputStream</param>
5                    <!-- 下载的InputStream流,Struts2自己动对应Action中的getVoiceFile方法,该方法必须返回InputStream 类型 -->
6                <param name="inputName">voiceFile</param>
7                <param name="bufferSize">2048</param>
8 </result>

 

          

 

jsp页面部分代码:

 

1 <s:iterator value="voiceList" status="index" id="fielInfo">
2   <tr>
3 
4     <td><s:property value="fileName"/></td>
5     <td><embed src="Controller_voice.action?currentFileFullName=<s:property value="fileFullName" />" autostart=false /></td>
6 
7   </tr>
8 </s:iterator>

 

 

posted @ 2014-05-01 18:23  明明是悟空  阅读(1089)  评论(0编辑  收藏  举报