0

In my current project I have encountered an interesting problem. I am trying to attach multiple files (pdf's, doc's etc. not only text files) to my SharePoint List, getting them from a document library. Problem is, when I use methods like get_web(), get_lists() etc. ending at get_file() from my current SP.ListItem, the type of file is SP.File (which is pretty obvious). In search for a solution I found this kind of method that uses SPServices:

http://www.bjw.co.nz/developer/sharepoint-2010/1188-spservices-addattachment-jquery-example

Here is the code:

    function handleFileChange(listName,itemId,files){
    var filereader = {},
        file = {},
        i=0;

    //loop over each file selected
    for(i = 0; i < files.length; i++) {
        file = files[i];            

        filereader = new FileReader();          
        filereader.filename = file.name;

        filereader.onload = function() {                
            var data = this.result,                     
                n=data.indexOf(";base64,") + 8; 

            //removing the first part of the dataurl give us the base64 bytes we need to feed to sharepoint
            data= data.substring(n);

            $().SPServices({
                operation: "AddAttachment",                 
                listName: listName,
                asynch: false,
                listItemID:itemId,
                fileName: this.filename,
                attachment: data,
                completefunc: function (xData, Status) {    
                    console.log('attachment upload complete',xData,status); 
                }
            });                 
        };

        filereader.onabort = function() {
            alert("The upload was aborted.");
        };

        filereader.onerror = function() {
            alert("An error occured while reading the file.");
        };              

        //fire the onload function giving it the dataurl
        filereader.readAsDataURL(file); 
    }
};

To use this solution I need to have an object of type File, not SP.File. My question is, how can I get the actual file from a SharePoint document library to complete my task? I couldn't find an answer anywhere, so even the smallest hint will be appreciated.

0

1 Answer 1

0

OK here is how to proceed (based on https://stackoverflow.com/questions/7370943/retrieving-binary-file-content-using-javascript-base64-encode-it-and-reverse-de):

// get the remote file binary content
function getBinary(file, callback) {
  var xhr = new XMLHttpRequest();  
  xhr.open("GET", file, true);
  xhr.overrideMimeType("text/plain; charset=x-user-defined")
  xhr.onreadystatechange = function (aEvt) {
    if (xhr.readyState == 4) {
      if(xhr.status == 200) {
        callback(xhr.responseText);
      } else {
        console.log("Cannot find the remote file")
      }
    }
  };
  xhr.send(null);
}

// convert the file content to a Base64 string
function base64Encode(str) {
  var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var out = "", i = 0, len = str.length, c1, c2, c3;
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      out += CHARS.charAt(c1 >> 2);
      out += CHARS.charAt((c1 & 0x3) << 4);
      out += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      out += CHARS.charAt(c1 >> 2);
      out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
      out += CHARS.charAt((c2 & 0xF) << 2);
      out += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    out += CHARS.charAt(c1 >> 2);
    out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    out += CHARS.charAt(c3 & 0x3F);
  }
  return out;
}

getBinary('http://your.site.com/879258.jpeg', function(binary) {
  var data = base64Encode(binary);
  // add the Base64 string version of the remote file to the list item
  $().SPServices({
    webURL: "http://your.site.com/",
    operation: "AddAttachment",                 
    listName: "List 1",
    async: true,
    listItemID: 315,
    fileName: "879258.jpg",
    attachment: data,
    completefunc: function (xData, Status) {    
      console.log('attachment upload complete',xData,status); 
    }
  });
})

I tried it and it worked!

1
  • in IE it is failing at below line, as IE doesn't have overrideMimeType method. xhr.overrideMimeType("text/plain; charset=x-user-defined") the same thing how can we work with IE, Your help is appreciated. Regards, Bishnu-
    – Bishnu Das
    Commented Feb 23, 2015 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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