在Struts 2中使用单个文件标签上传多个文件 [英] Multiple Files Upload using single file tag in Struts 2

查看:216
本文介绍了在Struts 2中使用单个文件标签上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



像在Gmail中一样,我们使用CTRL键附加多个文件来选择多个文件。

我知道如何上传多个文件,但是我想使用单个文件标签。

解决方案

<下面的示例程序演示了如何实现用Struts2框架上传多个文件的功能。该应用程序显示一个上传表单,允许用户选择一次上传三个文件。
上传的文件被复制到应用程序的 struts.xml 文件中配置的位置。

我们来看看示例应用程序被编码。
上传表单在 upload.jsp 页面中实现,如下所示:

 < ;%@ page language =javacontentType =text / html; charset = ISO-8859-1
pageEncoding =ISO-8859-1%>
<%@ taglib prefix =suri =/ struts-tags%>
<!DOCTYPE html PUBLIC - // W3C // DTD HTML 4.01 Transitional // ENhttp://www.w3.org/TR/html4/loose.dtd\">
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = ISO-8859-1>
< title>使用Struts2上传多个文件< / title>
< / head>
< body>
< center>
< h2>挑选多个档案上传< / h2>
< s:form action =uploadFileenctype =multipart / form-datamethod =post>
< s:file name =fileUploadmultiple =multiplelabel =Pick filessize =30/>
< br />
< s:submit value =全部上传/>
< / s:form>
< / center>
< / body>
< / html>

MultipleFilesUploadAction.java 文件中实现Struts2的动作类如下: p>

  import java.io.File; 
import java.io.IOException;

导入org.apache.commons.io.FileUtils;

public class MultipleFilesUploadAction {
private File [] fileUpload;
private String [] fileUploadFileName;
private String [] fileUploadContentType;
$ b $ **
*这是保存上传文件的路径,它是在struts.xml中配置的
* /
private String saveDirectory;
$ b $ public String doUpload(){

//将上传的文件复制到预先配置的位置
for(int i = 0; i< fileUpload.length ; i ++){
File uploadedFile = fileUpload [i];
String fileName = fileUploadFileName [i];
File destFile = new File(saveDirectory + File.separator + fileName);
尝试{
FileUtils.copyFile(uploadedFile,destFile);
catch(IOException ex){
System.out.println(Could not copy file+ fileName);
ex.printStackTrace();
}
}

返回成功;

$ b $ public File [] getFileUpload(){
return fileUpload;
}

public void setFileUpload(File [] fileUploads){
this.fileUpload = fileUploads;
}

public String [] getFileUploadFileName(){
return fileUploadFileName;
}

public void setFileUploadFileName(String [] fileUploadFileNames){
this.fileUploadFileName = fileUploadFileNames;


public String [] getFileUploadContentType(){
return fileUploadContentType;
}

public void setFileUploadContentType(String [] fileUploadContentTypes){
this.fileUploadContentType = fileUploadContentTypes;
}

public String getSaveDirectory(){
return saveDirectory;
}

public void setSaveDirectory(String saveDir){
this.saveDirectory = saveDir;




$ b $在这个POJO动作类中,我们使用三个数组存储上传的文件:

 私有文件[] fileUpload; 
private String [] fileUploadFileName;
private String [] fileUploadContentType;




  • 请注意, fileUpload 与upload.jsp文件中< s:file> 标签的名称
    属性的值匹配。 Struts2的
    拦截器调用fileUpload将通过setters获取这些变量
    的数据。
    变量saveDirectory的值通过相应的
    setter由Struts2的staticParams拦截器,这个值可以是在struts.xml文件中配置的

  • 动作类的入口方法 doUpload()将上传的文件
    从临时目录复制到
    saveDirectory 变量指定的位置,然后重定向到成功视图,即
    结果页面。

    $ b

    结果页面 result.jsp - 非常简单,显示成功message:

     <%@ page language =javacontentType =text / html; charset = ISO-8859-1 
    pageEncoding =ISO-8859-1%>
    <!DOCTYPE html PUBLIC - // W3C // DTD HTML 4.01 Transitional // ENhttp://www.w3.org/TR/html4/loose.dtd\">
    < html>
    < head>
    < meta http-equiv =Content-Typecontent =text / html; charset = ISO-8859-1>
    < title>上载结果< / title>
    < / head>
    < body>
    < center>
    < h2>档案已成功上载< / h2>
    < / center>
    < / body>
    < / html>

    我们通过应用程序的 struts连接上传表单页面,操作类和结果页面。 xml 文件如下:

     <?xml version =1.0encoding =UTF-8? > 
    <!DOCTYPE struts PUBLIC
    - // Apache Software Foundation // DTD Struts Configuration 2.0 // EN
    http://struts.apache.org/dtds/struts- 2.0.dtd>

    < struts>
    < constant name =struts.multipart.maxSizevalue =20971520/> <! - 20MB - >

    < package name =fileUploadextends =struts-default>

    < action name =uploadFileclass =com.example.struts.MultipleFilesUploadAction
    method =doUpload>

    < param name =saveDirectory> E:/ Test / Upload< / param>

    < interceptor-ref name =fileUpload>
    < param name =allowedTypes> * / *< / param>
    < param name =maximumSize> 4194304< / param> <! - 4MB - >
    < / interceptor-ref>

    < interceptor-ref name =staticParams/>
    < interceptor-ref name =params/>
    < interceptor-ref name =validation/>
    < interceptor-ref name =workflow/>

    < result name =successtype =redirect> /result.jsp< / result>
    < result name =input> /upload.jsp< / result>
    < / action>
    < / package>

    < / struts>




    • 这里,拦截器 fileUpload 被配置为允许所有文件
      类型可以被上传,并且单个文件的最大大小是
      4MB。
    • 常量 struts.multipart.maxSize 限制多个请求的最大大小
      是20MB。这意味着上传
      文件的总大小不能超过20MB。


    I want to upload multiple files using single Struts 2 file tag.

    Like in Gmail we attach multiple files using CTRL key to select multiple files.

    I know how to upload multiple files but I want to use single file tag.

    解决方案

    The following example program demonstrates how to implement functionality to upload multiple files with Struts2 framework. The application shows an upload form which allows user to pick up three files to upload at once. The uploaded files are copied into a location which is configured in application’s struts.xml file.

    Let’s see how the example application is coded. The upload form is implemented in the upload.jsp page as follows:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>   
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Multiple Files Upload with Struts2</title>
    </head>
    <body>
        <center>
            <h2>Pick multiple files to upload</h2>
            <s:form action="uploadFile" enctype="multipart/form-data" method="post">
                <s:file name="fileUpload" multiple="multiple" label="Pick files" size="30"/>
               <br/>
                <s:submit value="Upload All" />
            </s:form>
        </center>
    </body>
    </html>
    

    Implement Struts2’s action class in MultipleFilesUploadAction.java file as follows:

    import java.io.File;
    import java.io.IOException;
    
    import org.apache.commons.io.FileUtils;
    
    public class MultipleFilesUploadAction {
        private File[] fileUpload;
        private String[] fileUploadFileName;
        private String[] fileUploadContentType;
    
        /**
         * This is the path to save uploaded file, which is configured in struts.xml
         */
        private String saveDirectory;
    
        public String doUpload() {
    
            // copy the uploaded files into pre-configured location
            for (int i = 0; i < fileUpload.length; i++) {
                File uploadedFile = fileUpload[i];
                String fileName = fileUploadFileName[i];
                File destFile = new File(saveDirectory + File.separator + fileName);
                try {
                    FileUtils.copyFile(uploadedFile, destFile);
                } catch (IOException ex) {
                    System.out.println("Could not copy file " + fileName);
                    ex.printStackTrace();
                }
            }
    
            return "success";
        }
    
        public File[] getFileUpload() {
            return fileUpload;
        }
    
        public void setFileUpload(File[] fileUploads) {
            this.fileUpload = fileUploads;
        }
    
        public String[] getFileUploadFileName() {
            return fileUploadFileName;
        }
    
        public void setFileUploadFileName(String[] fileUploadFileNames) {
            this.fileUploadFileName = fileUploadFileNames;
        }
    
        public String[] getFileUploadContentType() {
            return fileUploadContentType;
        }
    
        public void setFileUploadContentType(String[] fileUploadContentTypes) {
            this.fileUploadContentType = fileUploadContentTypes;
        }
    
        public String getSaveDirectory() {
            return saveDirectory;
        }
    
        public void setSaveDirectory(String saveDir) {
            this.saveDirectory = saveDir;
        }
    }
    

    In this POJO action class, we use three arrays to store uploaded files:

    private File[] fileUpload;
    private String[] fileUploadFileName;
    private String[] fileUploadContentType;
    

    • Note that the word "fileUpload" matches with value of name attribute of <s:file> tag in the upload.jsp file. Struts2’s interceptor called fileUpload will fetch data for these variables through setters.
    • Value of the variable saveDirectory is set through corresponding setter by Struts2’s staticParams interceptor, and this value can be configured in struts.xml file.
    • The action class’ entry method doUpload() copies the uploaded files from temporary directory to the location specified by the saveDirectory variable, then redirect to a "success" view which is the result page.

    The result page result.jsp - is pretty simple, which shows a successful message:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Upload result</title>
    </head>
    <body>
        <center>
            <h2>The files were uploaded successfully</h2>
        </center>
    </body>
    </html>
    

    We connect the upload form page, the action class and the result page through application’s struts.xml file as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
    
    <struts>
        <constant name="struts.multipart.maxSize" value="20971520" /> <!-- 20MB -->
    
        <package name="fileUpload" extends="struts-default">
    
            <action name="uploadFile" class="com.example.struts.MultipleFilesUploadAction"
                method="doUpload">
    
                <param name="saveDirectory">E:/Test/Upload</param>
    
                <interceptor-ref name="fileUpload">
                    <param name="allowedTypes">*/*</param>
                    <param name="maximumSize">4194304</param> <!-- 4MB -->
                </interceptor-ref>
    
                <interceptor-ref name="staticParams"/>
                <interceptor-ref name="params" />
                <interceptor-ref name="validation" />
                <interceptor-ref name="workflow" />
    
                <result name="success" type="redirect">/result.jsp</result>
                <result name="input">/upload.jsp</result>
            </action>
        </package>
    
    </struts>
    

    • Here, the interceptor fileUpload is configured to allow all file types can be uploaded, and maximum size for an individual file is 4MB.
    • The constant struts.multipart.maxSize restricts maximum size allowed for a multipart request is 20MB. That means the total size of upload files cannot exceed 20MB.

    这篇关于在Struts 2中使用单个文件标签上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆