1、jsp页面:
<html:form action="/upload.do" method="post" enctype="multipart/form-data">
标题:<html:text property="title" value=""></html:text><br>
文件:<html:file property="file" value="" onchange="return checkName(this);"></html:file><br>
<html:button property="btn1" value="提交" onclick="return validate();" />
</html:form>
2、ActionForm
package com.solid.upload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm {
//文件标题
private String title;
//上传文件
private FormFile file;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
3、Action
package com.solid.upload;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
public class UploadAction extends DispatchAction {
public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
UploadForm uploadForm = (UploadForm)form;
//标题
String title = uploadForm.getTitle();
//文件
FormFile file = uploadForm.getFile();
try {
if(file != null) {
System.out.println("fileName=" + file.getFileName() + " fileSize=" + file.getFileSize());
String path = "D:" + java.io.File.separator + file.getFileName();
FileOutputStream fos = new FileOutputStream(path);
fos.write(file.getFileData());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return mapping.findForward("success");
}
}
本文介绍了一个使用Struts框架实现文件上传的例子。通过JSP页面收集用户输入的文件和标题,然后利用Struts的ActionForm和Action处理上传过程,并将文件保存到指定目录。该教程覆盖了从前端到后端的整个文件上传流程。
8038

被折叠的 条评论
为什么被折叠?



