struts2文件上传

使用struts2上传文件

1.首先你要配置好struts2项目的基本结构,引入struts2的lib包

2.配置web.xml,加入如下内容

    <filter>

        <filter-name>struts2</filter-name>

        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

    </filter>

 

    <filter-mapping>

        <filter-name>struts2</filter-name>

        <url-pattern>/*</url-pattern>

 

    </filter-mapping>

3.配置struts2.xml文件,在default package下加入如下内容

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

<action name="upload" class="com.it.action.fileuploadAction">

<result>/jsp/upload.jsp</result>

<result name="input">/jsp/error.jsp</result>

<!-- 配置拦截器 -->

<interceptor-ref name="fileUpload">

<param name="allowedTypes">image/bmp,image/x-png,image/jpeg</param>//上传文件的格式

<param name="maximumSize">2M</param>//上传文件的大小

</interceptor-ref>

<interceptor-ref name="defaultStack"></interceptor-ref>

</action>

 

    </package>

4.在上传页面的form表单上加入enctype="multipart/form-data" method="post"

5.写Action

package com.example;
 
    import java.io.File;
    import com.opensymphony.xwork2.ActionSupport;
 
    public class UploadAction extends ActionSupport {
       private File file;
       private String contentType;
       private String filename;
 
       public void setUpload(File file) {
          this .file = file;
       }
 
       public void setUploadContentType(String contentType) {
          this .contentType = contentType;
       }
 
       public void setUploadFileName(String filename) {
          this .filename = filename;
       }
 
       public String execute() {
          //...
          return SUCCESS;
       }
  }
属性必须包含以上3个,且set方法必须符合如下命名格式

Method Signature

Description

setX(File file)

The file that contains the content of the uploaded file. This is a temporary file and file.getName() will not return the original name of the file

setXContentType(String contentType)

The mime type of the uploaded file

setXFileName(String fileName)

The actual file name of the uploaded file (not the HTML name)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值