📅  最后修改于: 2021-01-11 06:22:55             🧑  作者: Mango
fileUpload拦截器会自动处理包含文件的所有请求。
我们可以使用此拦截器来控制struts2中文件上传的工作,例如定义允许的类型,最大文件大小等。
为文件上传拦截器定义了2个参数。
Parameter | Description |
---|---|
maximumSize | specifies maximum size of the file to be uploaded. |
allowedTypes | specifies allowed types. It may be image/png, image/jpg etc. |
它会在请求中自动添加2个参数:
fileName和contentType名称取决于文件的请求参数。如果filename是file,则需要使用fileFileName和fileContentType。如果filename是userImage,则需要在Action类中使用userImageFileName和userImageContentType。
让我们看看文件上传应用程序的目录结构。
该jsp页面使用struts UI标记创建表单。它从用户那里接收文件。
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
Upload User Image
Struts2 File Upload & Save Example without Database
该jsp页面使用struts UI标记创建表单。它从用户那里接收名称,密码和电子邮件ID。
<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s"
uri="/struts-tags"%>
Success: Upload User Image
Struts2 File Upload Example
User Image:
Content Type:
File Name:
Uploaded Image: "
width="100" height="100" />
该操作类继承了ActionSupport类并覆盖了execute方法。
package com.javatpoint;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File userImage;
private String userImageContentType;
private String userImageFileName;
public String execute() {
try {
String filePath = ServletActionContext.getServletContext().getRealPath("/").concat("userimages");
System.out.println("Image Location:" + filePath);//see the server console for actual location
File fileToCreate = new File(filePath,userImageFileName);
FileUtils.copyFile(userImage, fileToCreate);//copying source file to new file
return SUCCESS;
}
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public String getUserImageFileName() {
return userImageFileName;
}
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}
}
该xml文件通过名称输入和拦截器jsonValidatorWorkflowStack定义了额外的结果。
2097152
image/png,image/gif,image/jpeg,image/pjpeg
SuccessUserImage.jsp
UserImage.jsp
图像将不会显示在当前项目中。访问服务器控制台中打印的图像位置以查看图像。