Struts2上傳多個文件例子
在上章節Struts2 文件上傳示例, 用戶允許選擇一個文件並上傳到服務器。在本教程中,您將學習如何允許用戶將多個文件上傳到服務器。
這裏創建一個Web工程:strut2uploadfiles,來演示在多個複選框如何設置的默認值,整個項目的結構如下圖所示:
1. 動作類
在Action類,可以使用列表或數組以存儲上傳的文件。
FileUploadAction.java
package com.yiibai.common.action;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class MultipleFileUploadAction extends ActionSupport{
private List<File> fileUpload = new ArrayList<File>();
private List<String> fileUploadContentType = new ArrayList<String>();
private List<String> fileUploadFileName = new ArrayList<String>();
public List<File> getFileUpload() {
return fileUpload;
}
public void setFileUpload(List<File> fileUpload) {
this.fileUpload = fileUpload;
}
public List<String> getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(List<String> fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public List<String> getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(List<String> fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public String upload() throws Exception{
for (File file: fileUpload) {
System.out.println("File :" + file);
}
for (String fileName: fileUploadFileName) {
System.out.println("Filename : " + fileName);
}
for (String fileContentType: fileUploadContentType) {
System.out.println("File type : " + fileContentType);
}
return SUCCESS;
}
public String display() {
return NONE;
}
}
2. 結果頁面
使用<s:file>標籤來渲染多文件上傳組件,並設置表單 enctype類型爲「multipart/form-data」.
fileupload.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts2上傳多個文件示例
<s:form action="resultAction" namespace="/"
method="POST" enctype="multipart/form-data">
<s:file label="File 1" name="fileUpload" size="40" />
<s:file label="File 2" name="fileUpload" size="40" />
<s:file label="FIle 2" name="fileUpload" size="40" />
<s:submit value="submit" name="submit" />
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts2上傳多個文件示例
File Name :
Content Type :
File :
3. struts.xml
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="multipleFileUploadAction"
class="com.yiibai.common.action.MultipleFileUploadAction"
method="display">
<result name="none">pages/multiplefileupload.jsp</result>
</action>
<action name="resultAction"
class="com.yiibai.common.action.MultipleFileUploadAction"
method="upload">
<result name="success">pages/result.jsp</result>
</action>
4. 示例
http://localhost:8080/struts2uploafiles/multipleFileUploadAction.action
參考
- Struts2文件上傳示例
- Struts2文件上傳文檔
- http://struts.apache.org/2.0.14/docs/file-upload.html
- http://struts.apache.org/2.0.14/docs/how-do-we-upload-files.html
下載代碼 -