在
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