在
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> package actionform;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm
{
private FormFile myFile; // 這個myFile代表要上傳的檔案
public FormFile getMyFile()
{
return myFile;
}
public void setMyFile(FormFile myFile)
{
this.myFile = myFile;
}
}
【第3步】建立Struts動作類(Action的子類)
在Struts中,一般在Struts的動作類中處理上傳的檔案。在
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> package action;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import java.io.*;
import actionform.*;
public class UploadAction extends Action
{
protected void saveFile(FormFile formFile) throws Exception
{
// 從web.xml檔案中獲得指定的上傳路徑
String path = this.getServlet().getServletConfig().getInitParameter("uploadPath");
InputStream in = formFile.getInputStream(); // 獲得上傳檔案的InputStream
// 在服務端指定的上傳路徑中建立一個空的檔案(檔名為getFileName()方法返回的值)
FileOutputStream fout = new FileOutputStream(path + formFile.getFileName());
byte buffer[] = new byte[8192];
int count = 0;
// 開始向上傳路徑中剛建立的檔案寫入資料,每次寫8k位元組
while ((count = in.read(buffer)) > 0)
{
fout.write(buffer, 0, count);
}
fout.close();
formFile.destroy(); // 上傳成功後,銷燬當前上傳檔案的資源
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
UploadForm uForm = (UploadForm) form;
PrintWriter out = null;
try
{
response.setCharacterEncoding("GBK");
out = response.getWriter();
saveFile(uForm.getMyFile()); // 將上傳檔案儲存到指寫的路徑(在web.xml中配置)
out.println("上傳檔案成功.");
}
catch (Exception e)
{
out.println(e.getMessage());
}
return null;
}
}
Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4
在這一步來配置一下在第2步和第3步分別建立的ActionForm和Action的子類。開啟struts-config.xml檔案,在
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--><form-bean name="uploadForm" type="actionform.UploadForm" />
在
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> <action name="uploadForm" path="/uploadFile" scope="request" type="action.UploadAction" />
Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4
開啟web.xml檔案,找到一個叫action的Servlet(也就是用於處理Struts動作的Servlet),並在
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--><init-param>
<param-name>uploadPathparam-name>
<param-value>D:\upload\param-value>
init-param>
Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4
這一步是可選的,如果不限制上傳檔案的大小,就意味著可以上傳任意大小的檔案。而一般的應用程式,如電子相簿,網路硬碟都會限制上傳檔案的最大尺寸。
開啟struts-config.xml檔案,在
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> <controller maxFileSize="2M" />
Normal 0 7.8 磅 0 2 false false false MicrosoftInternetExplorer4
啟動Tomcat後,在IE中輸入如下的URL來測試程式:
http://localhost:8080/samples/uploadFile.jsp