我正在尝试使用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>
编辑:下次编辑帖子而不是在评论中发布代码......
答案 0 :(得分:1)
修改强>:
你的行动没有private File myFile;
的GETTER。
开始纠正......
问题可能在你的行动代码中,而不是在这里。
如果传递包含文件名/路径的字符串,它是什么意思?
你在Action中有一个带有公共访问者(getter和setter)的private File myFile;
(文件是java.io.File,而不是其他文件)吗?
看看这两个简单的教程:
http://viralpatel.net/blogs/struts-2-file-upload-save-tutorial-with-example/
http://www.roseindia.net/struts/struts2/struts-2-file-upload.shtml
答案 1 :(得分:0)
您将fileUpload
拦截器两次放入动作拦截器堆栈,因为defaultStack
已包含fileUpload
拦截器。您可以在堆栈中配置拦截器:
<action ...>
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<result ... />
</action>
还要确保在操作类中有变量的公共getter / setter。