我已按照this链接创建了一个包含Struts2的示例文件上传应用程序。样本效果很好。但是当我尝试使用AJAX上传图像时,我收到以下错误。
XMLHttpRequest cannot load http://localhost:8080/HeeloServer/userImage.action. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
这是我的动作类的代码。请注意,我对所有(*)来源使用response.addHeader()方法。我在其他没有问题的操作中有类似的代码,只有在使用AJAX上传Struts2文件时才会出现此错误。
package actions;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
private File userImage;
private String userImageContentType;
private String userImageFileName;
private String email;
private HttpServletRequest servletRequest;
public String execute() {
System.out.println("inside file upload action");
response.addHeader("Access-Control-Allow-Origin", "*");
try {
String filePath = servletRequest.getSession().getServletContext().getRealPath("/") + "photos/";
System.out.println("Server path: " + filePath);
System.out.println("Image to be uploaded " + userImageFileName);
System.out.println("Email" + email);
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setServletResponse(HttpServletResponse response){
this.response = response;
}
public HttpServletResponse getServletResponse(){
return response;
}
private HttpServletResponse response;
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
}