当前位置: 移动技术网 > IT编程>开发语言>Java > struts2实现简单文件下载功能

struts2实现简单文件下载功能

2019年07月19日  | 移动技术网IT编程  | 我要评论

struts2提供了stream结果类型,该结果类型是专门用于支持文件下载功能的。配置stream类型的结果需要指定以下4个属性。

  contenttype:指定被下载文件的文件类型

  inputname:指定被下载文件的入口输入流

  contentdisposition:指定下载的文件名

  buffersize:指定下载文件时的缓冲大小 

struts2文件下载示例:

1.处理文件下载的action:

/**
 * description:struts2控制文件下载
 * author: eleven
 * date: 2018/1/24 10:39
 */
public class fileaction extends actionsupport{

  //该成员变量对应着struts.xml中inputname的值,并为其提供get方法
  private inputstream targetfile;

  //文件下载
  public string download(){
    //指定被下载资源的位置,并返回对应的输入流
    string path = "/web-inf/images/lib.zip";
    //利用getresourceasstream()将指定文件转为对应的输入流
    targetfile = servletactioncontext.getservletcontext().getresourceasstream(path);
    return success;
  }

  //提供get方法
  public inputstream gettargetfile() {
    return targetfile;
  }
}

文件下载,首先得要有被下载的文件资源,这里我将被下载文件放在了项目的web-inf/images的路径下面,可根据自己的需求来,然后直接用servletcontext提供的getresourceasstream()方法返回指定文件对应的输入流。 

2.配置struts.xml

<?xml version="1.0" encoding="utf-8" ?>
<!doctype struts public
  "-//apache software foundation//dtd struts configuration 2.3//en"
  "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
  <constant name="struts.enable.dynamicmethodinvocation" value="false" />
  <constant name="struts.devmode" value="true" />

  <package name="default" namespace="/" extends="struts-default">

    <action name="file_*" class="eleven.action.fileaction" method="{1}">
      <!--文件下载-->
      <!--配置结果类型为stream的结果-->
      <result type="stream">
        <!--指定下载文件的文件类型-->
        <param name="contenttype">application/zip</param><!--image/jpg-->
        <!--指定action中返回被下载文件的inputstream的名称-->
        <param name="inputname">targetfile</param>
        <param name="contentdisposition">filename="aaa.zip"</param>
        <!--指定下载文件的缓冲大小-->
        <param name="buffersize">4096</param>
      </result>
    </action>

  </package>

</struts>

在浏览器地址栏中输入对应的文件下载的访问路径,如,即可下载文件了。\

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网