1

I am using SharePoint 2013 on premise. I am trying to upload file to the custom list from custom webpart purely jQuery and javascript. In my form I have hyperlink, when I click on it, it will open SharePoint Modal dialog. Where in I am making HTML5 drag & drop and trying to upload file.

This is my code HTML5, javascript with SharePoint REST api

(function(window) {
    function triggerCallback(e, callback) {
      if(!callback || typeof callback !== 'function') {
        return;
      }
      var files;
      if(e.dataTransfer) {
        files = e.dataTransfer.files;
      } else if(e.target) {
        files = e.target.files;
      }
      callback.call(null, files);
    }
    function makeDroppable(ele, callback) {
      var input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('multiple', false);
      input.style.display = 'none';
      input.addEventListener('change', function(e) {
        triggerCallback(e, callback);
      });
      ele.appendChild(input);

      ele.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.add('dragover');
      });

      ele.addEventListener('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.remove('dragover');
      });

      ele.addEventListener('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.remove('dragover');
        triggerCallback(e, callback);
      });

      ele.addEventListener('click', function() {
        input.value = null;
        input.click();
      });
    }
    window.makeDroppable = makeDroppable;
  })(this);
  (function(window) {
    makeDroppable(window.document.querySelector('.droppable'), function(files) {
        console.log(files);
        /*Check Files Length*/
        if (files.length > 1) {
            var msg = document.querySelector('.dz-message');
            msg.innerHTML += "<br/><span style='color:red'>You cannot upload more than 1 files</span>";
            return;
        }
        /*End*/
      var output = document.querySelector('.output');
      output.innerHTML = '';
      //for(var i=0; i<files.length; i++) {
      //  output.innerHTML += '<p>'+files[i].name+'</p>';
        //}
      //var formData = new FormData();
        //formData.append("files", files);
        var file = files[0];
        var getFileBuffer = function(file) {
            var deferred = $.Deferred();
            var reader = new FileReader();
            reader.onload = function (e) {
                deferred.resolve(e.target.result);
            }
            reader.onerror = function (e) {
                deferred.reject(e.target.error);
            }
            reader.readAsArrayBuffer(file);
            return deferred.promise();
        };
        var url = "_api/Web/Lists/getByTitle('GatePassDetails')/items(4)"
        uploadDocument(getFileBuffer, files[0].name, url)
    });
    function uploadDocument(buffer, fileName, url) {
        var url = String.format("{0}/{1}/AttachmentFiles/add(FileName='{2}')", _spPageContextInfo.webAbsoluteUrl, url, fileName);
        var call = jQuery.ajax({
            url: url,
            data: buffer,
            type: "POST",
            processData: false,
            headers: {
                Accept: "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "Content-Length": buffer.byteLength
            }
        });
    }

  })(this);

My codes works without any error but when I go to the list and try to open file than I will get error message as below after opening the file. enter image description here

Kindly can somebody help me to solve it.

  • It looks like you are passing the function getFileBuffer, not the results of calling getFileBuffer, as the first parameter to uploadDocument. Also, getFileBuffer is an asynchronous call, you need to wait for it to complete before you can call uploadDocument. – Rob Windsor Mar 29 '16 at 12:30
  • So what is the solution for it. How we can wait to complete the function – Milind Mar 29 '16 at 14:14
  • The article linked in my answer shows a complete solution (two in fact - one for CSOM and one for REST). To understand the code you need to understand asynchronous programming using jQuery promises. In the article, the author uses the jQuery then method to wait for the getFileBuffer method to complete. – Rob Windsor Mar 29 '16 at 15:50
3

You can't send the form data directly, you need to read it into an array buffer first.

var getFileBuffer = function (file) {     
    var deferred = $.Deferred();
    var reader = new FileReader();
    reader.onload = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(file);
    return deferred.promise();
}; 

For more information see: Uploading Files in SharePoint 2013 using CSOM and REST

  • Thanx for the answer I will check and let you know – Milind Mar 28 '16 at 12:19
  • It is the same issue. File is uploading but when I open it is corrupted. I will update my question with updated code – Milind Mar 29 '16 at 5:41
  • Any Help on this.............Please – Milind Mar 29 '16 at 11:44
  • Hi It was my mistake that I was not reading your reference article. As the function is from msdn, so I thought it is same. Thanks again. I could do the things in proper way. – Milind Mar 30 '16 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.