Struts 2是通過Commons FileUpload文件上傳。Commons FileUpload通過將HTTP的數據保存到臨時文件夾,然後Struts使用fileUpload攔截器將文件綁定到Action的實例中。從而我們就能夠以本地文件方式的操作浏覽器上傳的文件。
具體實現
前段時間Apache發布了Struts 2.0.6 GA,所以本文的實現是以該版本的Struts作為框架的。以下是例子所依靠類包的列表:
清單1 依靠類包的列表
首先,創建文件上傳頁面FileUpload.jsp,內容如下:
<% @ page language = " Java " contentType = " text/Html; charset=utf-8 " pageEncoding = " utf-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html XMLns ="http://www.w3.org/1999/xhtml" >
< head >
< title > Struts 2 File Upload </ title >
</ head >
< body >
< s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >
< s:file name ="myFile" label ="Image File" />
< s:textfield name ="caption" label ="Caption" />
< s:submit />
</ s:form >
</ body >
</ html >
清單2 FileUpload.jsp
在FileUpload.jsp中,先將表單的提交方式設為POST,然後將enctype設為multipart/form-data,這並沒有什麼非凡之處。接下來,<s:file/>標志將文件上傳控件綁定到Action的myFile屬性。
其次是FileUploadAction.java代碼:
package tutorial;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport {