I am using struts2 framework on server side. I am uploading a file using
server side :
client side :
function upload(){
var file = document.getElementById("fTU");
try {
this.xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
this.xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
this.xml = null;
}
}
if(!this.xml && typeof XMLHttpRequest != "undefined")
this.xml = new XMLHttpRequest();
if (!this.xml){
this.failed = true;
}
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
xml.open("POST", "", true);
xml.setRequestHeader("Content-Type", "false");
xml.send(formData); /* Send to server */
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
alert(xml.statusText);
}
}
}
How to fetch the uploaded file object on struts2 server side?
It is going in server side class and I am trying to retrieve file by using request.getParameter(upload) but it is giving null.
解决方案
I think you missed to add the Action Link in the xml.open() method. Take a look at the MDN to see some examples.
How does your Action-class look like? Have you defined a File field named upload with getter/setters?
Please also check, that your browser supports the FormData element, see question.
I also would suggest you to use a library like jQuery to simplify the Javascript code.
Action
public class FileUpload extends ActionSupport {
File myFile;
public String execute() {
//do some preparations for the upload
return SUCCESS;
}
public String upload() {
//only here the myFile is filled with data
return SUCCESS;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public File getMyFile() {
return myFile;
}
}
struts.xml
fileupload.jsp
fileupload.jsp
JSP
Javascript (taken from the MDN example above)
function upload() {
var fd = new FormData(document.querySelector("form"));
$.ajax({
url : "fileUpload", //this is the actionName
type: "POST",
data: fd,
processData: false,
contentType: false
});
return false; //to stop submitting the form
}
I have not tested this code, so please change it or add comments if something doesn't work.