在Java Web应用中,使用Struts框架的ActionForm类处理文件上传的过程如下:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
import org.apache.struts.action.ActionForm;
import java.io.File;
public class FileUploadForm extends ActionForm {
private File file;
// Getter and Setter methods for 'file' attribute
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
public class FileUploadAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
FileUploadForm fileUploadForm = (FileUploadForm) form;
// Validate the form
if (!fileUploadForm.validate()) {
return mapping.findForward("error");
}
// Create a FileUpload object
ServletFileUpload fileUpload = new ServletFileUpload();
// Parse the request
try {
List<FileItem> fileItems = fileUpload.parseRequest(request);
// Get the uploaded file
FileItem fileItem = fileItems.get(0);
File uploadedFile = new File(getServletContext().getRealPath("") + File.separator + fileItem.getName());
fileItem.write(uploadedFile);
return mapping.findForward("success");
} catch (IOException e) {
e.printStackTrace();
return mapping.findForward("error");
}
}
}
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="upload" class="com.example.FileUploadAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
现在,当用户通过表单上传文件时,Struts会将文件信息传递给FileUploadAction类,然后处理文件并将其保存到服务器上。