File Upload not working as expected with javascript,ajax, struts

I have an application where I have to upload files in a dynamic table. My code is as follows:

JSP code:

<td><s:file property="myFile" name="MasterBean" styleClass="File"/><input type="text" name="txtFakeText" id="txtFakeText"></td>
          <td><input type="button" onclick="HandleBrowseClick();" value="Browse" class="button"></td>
          <td><input name="fileUpload" id="fileUpload" type="button" value="Upload" class="button" onclick="UploadFileWithAjax();">

JS code:

 function HandleBrowseClick()
    var textinput = document.getElementById("txtFakeText");
    var fileinput = document.MasterBean.myFile;;
    textinput.value = fileinput.value;
    document.MasterBean.myFile = fileinput;

    function UploadFileWithAjax(){
      var urlvalue="";
      alert("file sent");

    function stateChangedupload(){
	if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
	    var showdata = xmlHttp.responseText;

    function GetXmlHttpObject(){
	var xmlHttp=null;
	  xmlHttp=new XMLHttpRequest();
	catch (e) {
	 try {
	  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	 catch (e){
	  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	return xmlHttp;

public class MasterBean extends ActionForm{
	//File upload
	private FormFile myFile;
	public FormFile getMyFile() {
		return myFile;
	public void setMyFile(FormFile myFile) {
		this.myFile = myFile;

    public class FileUpload extends DispatchAction {
    public ActionForward fileUpload(
		  ActionMapping mapping,
		  ActionForm form,
		  HttpServletRequest request,
		  HttpServletResponse response) throws Exception{
		  System.out.println("Inside fileUpload");	
		  MasterBean myForm = (MasterBean)form;

		  // Process the FormFile
		  FormFile myFormFile = myForm.getMyFile();
		  String contentType = myFormFile.getContentType();
		  String fileName  = myFormFile.getFileName();
		  int fileSize = myFormFile.getFileSize();
		  byte[] fileData  = myFormFile.getFileData();
		  System.out.println("contentType: " + contentType);
		  System.out.println("File Name: " + fileName);
		  System.out.println("File Size: " + fileSize);
		  File fileOnDisk = new File("/Users/Ben/Desktop/"+myFormFile.getFileName());

		  System.out.println("Path is "+fileOnDisk.getPath());

        FileOutputStream fileOutStream = new FileOutputStream(fileOnDisk);
        return mapping.findForward("upload");


My Problem is , This code works sometimes and does not on other times.

1.When it works… it uploads the first file and then when I retry uploading another file , it gives the details of the first file and uploads the first file again. The second file is not getting uploaded.

2.When it does not work , It gives a null pointer exception. and getMyFile() shows null in the console.

Can anyone please let me know what is wrong with my code? and explain me exactly what is happening here?? Thank You in Advance!