在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類,然后處理文件并將其保存到服務器上。