当前位置: 移动技术网 > IT编程>开发语言>Jsp > 使用Struts 2框架上传文件

使用Struts 2框架上传文件

2018年03月31日  | 移动技术网IT编程  | 我要评论

 

使用HTML表单上传文件的准备工作 

HTML表单默认值:

		<form action="" enctype="application/x-www-form-urlencoded" method="get">
      ...
</form>

要使用HTML表单上传文件,需要将HTML表单的enctype属性设置为"multipart/form-data",还需要将表单的method属性设置为"post"

		<form action="" enctype="multipart/form-data" method="post">
        ...
</form>

为了能使用户能够选择文件上传,表单中至少应该提供一个<input type="file">字段:

		<form action="multi_upload.action" enctype="multipart/form-data" method="post" id="uploadForm"> 
    Choose a file to Upload:<input type="file" name="file"/><br />
    <input type="submit" value="submit"/>
</form>

浏览器显示的效果:

\


使用Struts 2框架上传文件的准备工作

第一步、在JSP页面中使用Struts 2标签库中的file标签,给它取一个容易理解的名字,若要上传多个文件就必须使用多个file标签,但它们的名字必须相同:

		<s:form action="multi_upload" method="post" enctype="multipart/form-data">
    <s:file name="attachment" label="Attachment 1"/>
    <s:file name="attachment" label="Attachment 2"/>
    <s:file name="attachment" label="Attachment 3"/>
    <s:submit value="submit"/>
</s:form>

Struts 2的file标签,在浏览器中会被映射为<input type="file" name="attachment">。

第二步、创建接收上传文件信息的动作类。该动作类被约定为必须带有3个属性,并且这三个属性的命名必须符合是下面的规定

  •  [inputName]File
  •  [inputName]FileName
  •  [inputName]ContentType

这里的[inputName]是表单上file标签的名字,例如,file标签的name="attachment",你的这三个属性的名字必须命名为attachmentFile、attachmentFileName和attachmentContentType。

若只是上传单个文件,则[inputName]File属性的类型为 Java.io.File,它代表的是上传的文件,第二个和第三个属性都为String类型,他们分别代表被上传文件的文件名和内容类型。若要上传多个文件,则可以使用数组或Java.util.List。

		private File[] attachmentFile;
private String[] attachmentFileName;
private String[] attachmentContentType;

		private List<File> attachmentFile;
private List<String> attachmentFileName;
private List<String> attachmentContentType;

第三步、将上传的文件保存到一个指定的文件夹下或数据库中。


示例:Struts 2单文件上传

接收上传文件的动作类:

		public class SingleFileUploadAction extends ActionSupport
{
    private static final long    serialVersionUID    = 742220866388022377L;

    private File                 attachment;                                // 用户上传的文件
    private String               attachmentFileName;                        // 上传文件的文件名
    private String               attachmentContentType;                     // 上传文件的类型
    private String               description;                               // 用户的描述

    /*
     * SingleFileUploadAction的属性的getter和setter方法
     */
    public File getAttachment()
    {
        return attachment;
    }

    public void setAttachment(File attachment)
    {
        this.attachment = attachment;
    }

    public String getAttachmentFileName()
    {
        return attachmentFileName;
    }

    public void setAttachmentFileName(String attachmentFileName)
    {
        this.attachmentFileName = attachmentFileName;
    }

    public String getAttachmentContentType()
    {
        return attachmentContentType;
    }

    public void setAttachmentContentType(String attachmentContentType)
    {
        this.attachmentContentType = attachmentContentType;
    }

    public String getDescription()
    {
        return description;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public String execute() throws Exception
    {
        if (attachment != null)
        {
            String dataDir = "d:\\images";// 上传文件存放的目录
            File savedFile = new File(dataDir, attachmentFileName);// 上传文件在服务器具体的位置
            attachment.renameTo(savedFile);// 将上传文件从临时文件复制到指定文件
        }
        else
        {
            return INPUT;
        }

        return SUCCESS;
    }
}

上传文件的表单:

		<s:form action="single_upload" method="post" enctype="multipart/form-data">
    <s:textfield name="description" label="description"></s:textfield>
    <s:file name="attachment" label="Choose a File to Upload"></s:file>
    <s:submit value="submit"></s:submit>
</s:form>

struts.xml的配置信息:

		<action name="single_upload" class="struts2.suxiaolei.fileupload.action.SingleFileUploadAction">
    <result name="success">/success_single_upload.jsp</result>
    <result name="input">/single_upload.jsp</result>
            
    <interceptor-ref name="defaultStack">
        <param name="fileUpload.maximumSize">100000</param>
        <param name="fileUpload.allowedTypesSet">image/gif,image/jpeg,image/png</param>
    </interceptor-ref>
</action>

测试:

浏览器输入http://localhost:8081/Struts2/single_upload.jsp,得到如下页面:

\

填写信息和选择一个需要上传的文件

\

点击"submit"按钮上传文件,查看D盘下images文件夹下的文件:

\

 上传单个文件成功!


示例:动态多文件上传

创建HTML表单

		<form action="multi_upload.action" enctype="multipart/form-data" method="post">
    <table>
        <tr>
            <td>
                Choose a file to Upload:
            </td>
            <td id="more">
                <input type="file" name="file"/><input type="button" value="Add More..."onclick="addMore();"/>
            </td>
        </tr>

        <tr>
            <td>
            </td>
            <td>
                <input type="submit" value="submit"/>
            </td>
        </tr>
    </table>
</form>

创建JavaScript代码,使表单能动态增减上传文件的个数

		<script type="text/javascript">
    
    function addMore()
    {
        var td = document.getElementById("more");//获取id="more"的元素,该元素用于容纳动态增减的上传文件元素
        
        var br = document.createElement("br");//创建<br />元素
        var input = document.createElement("input");//创建<input>元素,设置该元素的属性为<input type="file" name="file" />,用于选择上传的文件
        var button = document.createElement("input");//创建<input>元素,设置该元素的属性为<input type="button" value="remove" />,用于移除上传标签
        
        input.type = "file";
        input.name = "file";
        
        button.type = "button";
        button.value = "remove";
        
        //移除上传标签
        button.onclick = function()
        {
            td.removeChild(br);
            td.removeChild(input);
            td.removeChild(button);
        };
        
        /*
         * 添加上传标签
         */
        td.appendChild(br);
        td.appendChild(input);
        td.appendChild(button);
    }
    
    </script>

接收多个上传文件的动作类:

		public class MultiFileUploadAction extends ActionSupport
{
    private static final long    serialVersionUID    = -5056971793538814980L;

    private List<File>           fileFile;
    private List<String>         fileFileName;
    private List<String>         fileContentType;

    public List<File> getFileFile()
    {
        return fileFile;
    }

    public void setFileFile(List<File> fileFile)
    {
        this.fileFile = fileFile;
    }

    public List<String> getFileFileName()
    {
        return fileFileName;
    }

    public void setFileFileName(List<String> fileFileName)
    {
        this.fileFileName = fileFileName;
    }

    public List<String> getFileContentType()
    {
        return fileContentType;
    }

    public void setFileContentType(List<String> fileContentType)
    {
        this.fileContentType = fileContentType;
    }

    @Override
    public String execute()
    {
        if (fileFile.size() == 0)
        {
            return INPUT;
        }
        else
        {

            for (int index = 0; index < fileFile.size(); index++)
            {
                String targetDir = "d:\\images";
                File savedFile = new File(targetDir, fileFileName.get(index));
                fileFile.get(index).renameTo(savedFile);
            }
        }

        return SUCCESS;
    }

}

struts.xml配置信息:

		<action name="multi_upload" class="struts2.suxiaolei.fileupload.action.MultiFileUploadAction">
    <result name="success">/success_multi_upload.jsp</result>
    <result name="input">/multi_upload.jsp</result>
            
    <interceptor-ref name="defaultStack">
        <param name="fileUpload.maximumSize">100000</param>
        <param name="fileUpload.allowedTypesSet">image/gif,image/jpeg,image/png</param>
    </interceptor-ref>
</action>

success_multi_upload.jsp:

		<s:property value="fileFileName"/> Upload Successfully!

测试:

浏览器中输入:http://localhost:8081/Struts2/multi_upload.jsp,获得如下界面:

\

点击"Add More..."按钮,我们要上传10个文件:

\

可以看到现在页面动态的增加了上传文件的个数,我们还可以点击"remove"按钮动态减少上传文件的个数,下面选择上传文件:

\

点击"submit"按钮上传文件:

\

查看D盘下images文件夹:

\

可以看到我们选择的文件都上传成功了!


Struts 2上传文件的工作原理和注意事项

    Struts 2框架是通过使用fileUpload拦截器实现文件上传操作的,当fileUpload拦截器执行时,它处理一个多重请求"multipart request"并且将文件与其他一些元素一起转换到请求参数中。

fileUpload拦截器提供的请求参数:

                  参数名称                                参数类型                                 代表含义
            [来源于表单的文件名]                            File                                  被上传的文件
       [来源于表单的文件名]ContentType             String                              文件的内容类型
       [来源于表单的文件名]FileName                String               文件的名称

在fileUpload拦截器将请求参数作为多重请求的一部分公开后,就轮到栈中下一个拦截器工作了。下一个拦截器是params拦截器。当params拦截器触发时,他把所有的请求参数都移动到动作对象上。这样,为了便利的接收上传文件,开发人员需要提供与fileUpload拦截器提供参数名字匹配的JavaBean属性。

fileUpload拦截器有两个重要的属性:

  • maximumSize:上传文件的最大长度(以字节为单位),默认值大约是2MB。
  • allowedTypesSet:允许上传的内容类型的清单,各类型之间以逗号分隔。

通过设置这两个属性,你可以对上传文件的长度和允许上传的内容类型进行限制。如果用户上传的文件尺寸大于给定的最大长度或内容类型没被列在allowedTypesSet参数里,将会显示一条错误信息。


我使用的版本为struts-2.2.3.1版本若fileUpload拦截器配置参数不匹配将allowedTypesSet 改为 allowedTypes 就可以

 

作者 消逝の纸屑

<script></script>

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

相关文章:

验证码:
移动技术网