Search code examples
javascripthtmljsoniframeinternet-explorer-9

Upload file using iFrame for IE9


Html:

<form id="formLogo">
<input type="file" id="logo" name="logo" accept="image/x-png, image/gif, image/jpeg" />
</form>

javascript:

  var myForm = new FormData();
  myForm .append("file", $("#logo").files[0]);
  myForm .append("type", "company");
  myForm .append("accountId", "3124234");
  $.ajax({
      url: '/efrcetrdmbo/app/file/upload',
      data: myFormData,
      dataType: 'text',
      processData: false,
      contentType: false,
      type: 'POST',
      success: function (data) {
          alert("sucess");
      }
  });

FormData is not supported in IE9. I want to use iFrame to upload file and some other data with it.


Solution

  • Instead of having the iframe in html, creating it before upload and than deleting.

    Providing correct url, files are uploaded.

    JS:

    function fileUpload(form, action_url) {
        var iframe = document.createElement("iframe");
        iframe.setAttribute("id", "frame");
        iframe.setAttribute("name", "frame");
        iframe.setAttribute("width", "0");
        iframe.setAttribute("height", "0");
        iframe.setAttribute("frameborder", "0");
    
        form.parentNode.appendChild(iframe);
    
        iframeId = document.getElementById("frame");
    
        var eventHandler = function () {
    
            if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
            else iframeId.removeEventListener("load", eventHandler, false);
    
            if (iframeId.contentDocument) {
                content = iframeId.contentDocument.body.innerHTML;
            } else if (iframeId.contentWindow) {
                content = iframeId.contentWindow.document.body.innerHTML;
            } else if (iframeId.document) {
                content = iframeId.document.body.innerHTML;
            }
    
            setTimeout('iframeId.parentNode.removeChild(iframeId)', 200);
        }
    
        if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
        if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
    
        form.setAttribute("target", "frame");
        form.setAttribute("action", action_url);
        form.setAttribute("method", "post");
    
        form.submit();
    }
    

    Html:

    <form>
        <input type="file" name="file" /></br>
        <input type="button" value="upload" onClick="fileUpload(this.form,'url'); return false;" >
    </form>