文件下载使用的getResourceAsStream

getResourceAsStream

转(谢谢热心网友的帖子)

 

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

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

所 以,如果写:
getResourceAsStream("/resource.xml");
则要保证classpath下有 resource.xml文件就能找到。

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

 

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

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

 

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

action 中的java 部分代码:

public InputStream getVoiceFile() throws FileNotFoundException {
           return new FileInputStream(this.getCurrentFileFullName());

           //return ServletActionContext.getServletContext().getResourceAsStream(this.getCurrentFileFullName());
    }

public String voice(){
        return "voice";
    }

 

struts.xml中部分代码:

 

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

 

jsp页面部分代码:

 

<s:iterator value="voiceList" status="index" id="fielInfo">
<tr>

<td><s:property value="fileName"/></td>
<td><embed src="Controller_voice.action?currentFileFullName=<s:property value="fileFullName" />" autostart=false /></td>

</tr>
</s:iterator>

posted @ 2016-03-29 14:43  guodaxia  阅读(370)  评论(0)    收藏  举报