当前位置: 移动技术网 > IT编程>开发语言>Java > java中Struts2 的文件上传和下载示例

java中Struts2 的文件上传和下载示例

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

文件上传

  1. 表单准备
    • 要想使用 html 表单上传一个或多个文件
    • 须把 html 表单的 enctype 属性设置为 multipart/form-data
    • 须把 html 表单的method 属性设置为 post
    • 需添加 <input type=“file”> 字段.
  2. struts 对文件上传的支持
    • 在 struts 应用程序里, fileupload 拦截器和 jakarta commons fileupload 组件可以完成文件的上传.
    • 步骤:
      1. 在 jsp 页面的文件上传表单里使用 file 标签. 如果需要一次上传多个文件, 就必须使用多个 file 标签, 但它们的名字必须是相同的
      2. 在 action 中新添加 3 个和文件上传相关的属性. 这 3 个属性的名字必须是以下格式
        • 基本的文件的上传: 直接在 action 中定义如下 3 个属性, 并提供对应的 getter 和 setter
        • [file name] : 类型-file -被上传的文件。例如:data(filename要求和文件表单项的name一致
        • [file name]contenttype : 类型-string -上传文件的文件类型。例如:datacontenttype(用来接收文件类型(mime值)
        • [file name]filename : string -上传文件的文件名。例如:datafilename (用来接收文件的名字
      3. 如果上传多个文件, 可以使用 list
        • 若传递多个文件, 则上述的 3 个属性, 可以改为 list 类型! 多个文件域的 name 属性值需要一致.
  3. 示例代码
<s:form action="testupload" enctype="multipart/form-data">
  <s:textfield name="username[0]" label="用户-1"></s:textfield>
  <s:file name="photos" label="照片"></s:file>
  <s:textfield name="username[1]" label="用户-2"></s:textfield>
  <s:file name="photos" label="照片"></s:file>
  <s:textfield name="username[2]" label="用户-3"></s:textfield>
  <s:file name="photos" label="照片"></s:file>
  <s:submit value="提交"></s:submit>
</s:form> 
public class uploadaction extends actionsupport{

  @setter@getter
  private list<file> photos;
  @setter@getter
  private list<string> photoscontenttype;
  @setter@getter
  private list<string> photosfilename;
  @setter@getter
  private list<string> username;

  public string testupload() throws ioexception {
    system.out.println("username: "+username);
    system.out.println("photos: "+photos);
    system.out.println("photosfilename: "+ photosfilename);
    system.out.println("photoscontenttype: "+photoscontenttype);

    // 将文件传到服务器根目录下upload文件下
    // 获取servletcontext
    servletcontext servletcontext = servletactioncontext.getservletcontext();
    //获取真实路径
    string realpath = servletcontext.getrealpath("/upload");
    system.out.println(realpath);
    file uploadfile = new file(realpath);
    //判断路径是否存在
    if (!uploadfile.exists()){
      //不存在创建
      uploadfile.mkdir();
    }
    for (int i = 0; i < photos.size(); i++) {
      uuid uuid = uuid.randomuuid();
      fileutils.copyfile(photos.get(i), new file(realpath + "/" + uuid + photosfilename.get(i)));
    }
    return success;
  }
}

1.处理几个小问题?

1.文件名重名,一般可以在文件名的前面生成一个uuid作为前缀。

2.限制单个文件的大小

3.限制文件的类型

4.限制总文件的大小

2.在struts2 中提供了 fileupload 拦截器 可以给我们设置这些属性值

 fileupload 拦截器有 3 个属性可以设置.

  •  maximumsize: 上传单个文件的最大长度(以字节为单位), 默认值为 2 mb
  • allowedtypes: 允许上传文件的类型, 各类型之间以逗号分隔
  • allowedextensions: 允许上传文件扩展名, 各扩展名之间以逗号分隔
  • 可以在 struts.xml 文件中覆盖这 3 个属性

注意: 在 org.apache.struts2 下的 default.properties 中有对上传的文件总的大小的限制. 可以使用常量的方式来修改该限制struts.multipart.maxsize=2097152

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

 <!-- 在这修改总文件的的大小 -->
 <constant name="struts.multipart.maxsize" value="2097152"/>
 <package name="default" namespace="/" extends="struts-default">
  <interceptors>
    <interceptor-stack name="myinterceptor">
      <interceptor-ref name="defaultstack">
        <!-- 修改单个文件大小,commons fileupload 组件默认接受上传文件总的最大值为 2m -->
        <param name="fileupload.maximumsize">57,408</param>
        <!-- 允许上传的文件类型 -->
        <param name="fileupload.allowedtypes">image/pjpeg,image/gif</param>
        <!-- 允许上传文件的扩展名 -->
        <param name="fileupload.allowedextensions">jpg,gif</param>
      </interceptor-ref>
    </interceptor-stack>
  </interceptors>

  <default-interceptor-ref name="myinterceptor"></default-interceptor-ref>
  
  <action name="testupload" class="org.pan.action.uploadaction" method="testupload">
    <result name="success">/web-inf/views/success.jsp</result>
    <result name="input">/upload.jsp</result>
  </action>
</package>

一.上传文件相关的错误消息?

1.与文件上传有关的出错消息在 struts-messages.properties 文件里预定义.

2.可以在文件上传 action 相对应的资源文件 或者 在 i18n_zh_cn.properties 国际化资源文件中重新定义错误消息

struts.messages.error.file.too.large=你传的文件太大了
struts.messages.error.content.type.not.allowed=文件类型错误
struts.messages.error.file.extension.not.allowed=扩展名错误
struts.messages.upload.error.sizelimitexceededexception=文件总大小超过上限

文件下载

  1. 在某些应用程序里, 可能需要动态地把一个文件发送到用户的浏览器中, 而这个文件的名字和存放位置在编程时是无法预知的

  2. stream 结果类型
    • struts 专门为文件下载提供了一种 stream 结果类型. 在使用一个 stream 结果时, 不必准备一个 jsp 页面.
    • stream 结果类型可以设置如下参数:
      • contenttype:被下载的文件的 mime 类型。默认值为 text/plain
      • contentlength:被下载的文件的大小,以字节为单位
      • contentdisposition: 可以设置下载文件名的contentdispositon 响应头,默认值为 inline,通常设置为如下格式:
        • attachment;filename="document.pdf".
      • inputname:action 中提供的文件的输入流。默认值为 inputstream
      • buffersize:文件下载时缓冲区的大小。默认值为 1024
      • allowcaching :文件下载时是否允许使用缓存。默认值为 true
      • contentcharset:文件下载时的字符编码。
        • 以上参数可以在 action 中以 getter 方法的方式提供!
    • stream 结果类型的参数可以在 action 以属性的方式覆盖
    • 具体使用细节参看 struts-2.3.15.3-all/struts-2.3.15.3/docs/ww/docs/stream-result.html
  3. 示例代码

<a href="testdownload">下载</a>
public class downloadaction extends actionsupport{
  //通常以下这几个参数会在action 中提供
  @setter@getter
  private string contenttype;
  @setter@getter
  private long contentlength;
  @setter@getter
  private string contentdisposition;
  @setter@getter
  private inputstream inputstream;

  public string testdownload() throws filenotfoundexception, unsupportedencodingexception {
    //获取servletcontext
    servletcontext servletcontext = servletactioncontext.getservletcontext();
    //获取文件的路径
    string realpath = servletcontext.getrealpath("/web-inf/file/至少还有你.mp3");
    //获取文件的流
    inputstream = new fileinputstream(realpath);
    //设置文件的类型
    contenttype = servletcontext.getmimetype(realpath);
    //获取文件的长度
    contentlength = new file(realpath).length();
    //设置文件名
    string filename = "至少还有你.mp3";
    filename = new string(filename.getbytes("gbk"),"iso8859-1");
    contentdisposition = "attachment;filename="+filename;
    return success;
  }
}

<!-- 文件下载 -->
<action name="testdownload" class="org.pan.action.downloadaction" method="testdownload">
  <result type="stream">
    <!-- 文件缓冲大小 -->
    <param name="buffersize">2048</param>
  </result>
</action>

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

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

相关文章:

验证码:
移动技术网