我正在尝试使用Jquery ajax在struts 2中上传文件。使用表单提交我能够。请帮助我。 JSP的代码如下所示
<script type="text/javascript">
function upload()
{
$.ajax({
type : "POST",
url : 'userImage.action',
dataType:'text',
data:$("#uploadForm").serialize(),
async:false,
success : function(data) {
alert(data)
}
});
}
</script>
</head>
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<form id="uploadForm" action="userImage" method="post" enctype="multipart/form-data">
<input type="file" name="userImage" /><br>
<input type="button" value="submit" onclick="upload()">
</form>
</body>
</html>
struts2.xml中给出的代码在下面给出
<action name="userImage"
class="hart.bean.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">SuccessUserImage.jsp</result>
<result name="input">UserImage.jsp</result>
</action>
行动类中的代码如下所示
private File userImage;
private String userImageContentType;
private String userImageFileName;
private HttpServletRequest servletRequest;
public String execute() {
try {
String filePath = servletRequest.getSession().getServletContext().getContextPath();
System.out.println("Server path:" + filePath+" userimg=="+userImageFileName);
File fileToCreate = new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
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;
}
@Override
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
答案 0 :(得分:0)
当我在互联网上搜索时,发现我无法使用XMLHttpRequest(Ajax)上传文件。因此,我使用了一个jquery Form Plugin。