Search This Blog

Wednesday, August 31, 2016

SharePoint JS: Upload a file using javascript, jQuery, HTML5

To upload a file using jquery, i used this code:


//Function attached to the html fileupload tag (<input type="file">)
function uploadFile(){
    if (document.getElementById("inputFile").files.length === 0) {
        alert('No file was selected');
        return;
    }
    var parts = document.getElementById("inputFile").value.split("\\");
    var filename = parts[parts.length - 1];
    var file = document.getElementById("inputFile").files[0];
    uploadFileSync("http://ngo.com", "libraryname", filename, file);
}

//Upload file synchronously
function uploadFileSync(spWebUrl , library, filename, file) 
{
    var reader = new FileReader();
    reader.onloadend = function(evt) 
    {
      if (evt.target.readyState == FileReader.DONE) 
      {
         var buffer = evt.target.result;
         var completeUrl = spWebUrl
           + "/_api/web/lists/getByTitle('"+ library + "')"
           + "/RootFolder/Files/add(url='"+ filename +"',overwrite='true')?"
           + "@TargetLibrary='"+library+"'&@TargetFileName='"+ filename +"'";

          $.ajax({
                url: completeUrl,
                type: "POST",
                data: buffer,
                async: false,
                processData: false,
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "content-length": buffer.byteLength
                },
                complete: function (data) {
                    alert('succes');
                },
                error: function (err) {
                     alert('failed');
                }
        });
      }
    };
    reader.readAsArrayBuffer(file);
}

Resources

  • jQuery
  • HTML5 - FileReader
  • Note- If Validation Setting on Library This Code is Not Working
  • Request failed. List data validation failed.undefined

  • Error Message:

    Request failed. List data validation failed.undefined

    Problem Description:

    I wrote JavaScript function to add item into SharePoint List but I getting below error shown in following figure.





    I got above error because I kept column validation in my one of the Date Column,





    I remove column level validation from my List, I wrote validation in JavaScript function only.





    That’s all and finally my Item created using JavaScript…


    

No comments:

Post a Comment