我正在尝试使用 S:file 标签上传文件,但它给了我 http 500 内部错误。但是当我在同一代码中直接将文件名和路径作为常量时,它可以工作。所以我不确定我在哪里错过了循环孔。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Struts 2 - Login Application | ViralPatel.net</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="uploadFile.action" method="post" enctype="multipart/form-data" >
<s:textfield name="myName"></s:textfield>
<s:file name="myFile"></s:file>
<s:submit value="Submit" align="center" />
</s:form>
</body>
</html>
行动
class FileUploadAction extends ActionSupport implements ServletRequestAware {
File userImage;
String userImageContentType;
String userImageFileName;
HttpServletRequest servletRequest;
public String execute() {
try {
String filePath = servletRequest.getSession()
.getServletContext().getRealPath("/");
File fileToCreate = new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
} catch (Exception e) {
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
public void setServletRequest(HttpServletRequest servletRequest) {
servletRequest = servletRequest;
}
}
配置
<action name="userImage" class="net.viralpatel.struts2.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack">
</interceptor-ref>
<result name="success">SuccessUserImage.jsp</result>
<result name="input">UserImage.jsp</result>
</action>
编辑:下次编辑您的帖子而不是在评论中发布代码......