azaveri7 azaveri7 - 3 months ago 11
Ajax Question

How to retrieve uploaded file using ajax on java server side?

I am using struts2 framework on server side. I am uploading a file using

server side :

<s:file name="fTU" id="fTU"/>

<input type="submit" value ="ok" onclick="upload()">


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.

Answer

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

<!-- init method to show the form -->
<action name="fileForm" class="...FileUpload">
    <result name="success">fileupload.jsp</result>
</action>

<!-- upload method to upload the file -->
<action name="fileUpload" class="...FileUpload" method="upload">
    <result name="success">fileupload.jsp</result>
</action>

JSP

<s:form enctype="multipart/form-data" method="post" name="fileinfo" action="fileUpload">
    <s:file name="myFile"/>
</s:form>

<input type="submit" onClick="upload()" value="OK"> 

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.