struts2文件下载

文件能上传当然也能下载了,下面是一个下载文件的例子,万变不离其宗,所以对于其他文件的下载,只要改变一些参数和配置就可以了。

以下代码都是可以运行的。

这是jsp页面的部分代码:

  <</span>form action="${pageContext.request.contextPath}/ttt/downlord.action">

  文件路径:<</span>input type="text" name="inputPath" value="/uploads/test.zip"/><</span>br/>

  文件名称:<</span>input type="text" name="fileName" value="test.zip"/><</span>br/>

  <</span>input type="submit" value="下载"/><</span>br/>

  </</span>form>

 

 

这是文件下载的Action

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

 

import org.apache.struts2.ServletActionContext;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class DownloadFile extends ActionSupport {

       public String getInputPath() {

              return inputPath;

       }

 

       public void setInputPath(String inputPath) {

              this.inputPath = inputPath;

       }

 

       public String getFileName() {

              return fileName;

       }

 

       public void setFileName(String fileName) {

              this.fileName = fileName;

       }

 

       private String inputPath;

       private String fileName;

 

       public InputStream getInputStream() throws Exception{

              return ServletActionContext.getServletContext().getResourceAsStream(inputPath);

       }

      

       @Override

       public String execute() throws Exception {

              if(!inputPath.startsWith("/WEB-INF")){

                     return SUCCESS;

              }

              return null;

       }

       public String getDownloadFileName(){

              String downFileName=fileName;

              try {

                     downFileName=new String(downFileName.getBytes(),"ISO8859-1");

              } catch (UnsupportedEncodingException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

              return downFileName;

       }

}

 

 

 

这是文件下载的配置文件:

<</span>action name="downlord" class="com.defu.com.DownloadFile">

<</span>result name="success" type="stream">

<</span>param name="contentType">application/octet-stream;charset=ISO8859-1</</span>param>

<</span>param name="inputName">inputStream</</span>param>

<</span>param name="contentDisposition">attachment;filename=${downloadFileName}</</span>param>

<</span>param name="bufferSize">4096</</span>param>

</</span>result>

</</span>action>

当然,文件下载也可能是其他文件类型,只要改变一些红色的 contentType 中的参数就可以了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值