3

is there a way to upload file as attachment while using JavaScript client object model in sharepoint 2013? Or using web service in the middle is required? I cannot use FileAPI from HTML5.

Thank you for any ideas.

3

Yes..I found this blog post very usefull...

Using JSOM to write (small) files to a SharePoint 2013 document library

Basically the code you need is as follows:

$(document).ready(function ()
{
// Get the URI decoded host web URL
// We will use this to get a context here to write data
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
});

 function CreateFile()
{
// Ensure the HTML5 FileReader API is supported
if (window.FileReader)
{
    input = document.getElementById("fileinput");
    if (input)
    {
        file = input.files[0];
        fr = new FileReader();
        fr.onload = receivedBinary;
        fr.readAsDataURL(file);
    }
}
else
{
    alert("The HTML5 FileSystem APIs are not fully supported in this browser.");
}
}

// Callback function for onload event of FileReader
function receivedBinary()
{
// Get the ClientContext for the app web
clientContext = new SP.ClientContext.get_current();
// Use the host web URL to get a parent context - this allows us to get data from the parent
parentCtx = new SP.AppContextSite(clientContext, hostweburl);
parentWeb = parentCtx.get_web();
parentList = parentWeb.get_lists().getByTitle("Documents");

fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(file.name);
fileCreateInfo.set_overwrite(true);
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());

// Read the binary contents of the base 64 data URL into a Uint8Array
// Append the contents of this array to the SP.FileCreationInformation
var arr = convertDataURIToBinary(this.result);
for (var i = 0; i < arr.length; ++i)
{
    fileCreateInfo.get_content().append(arr[i]);
}

// Upload the file to the root folder of the document library
this.newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);

clientContext.load(this.newFile);
clientContext.executeQueryAsync(onSuccess, onFailure);
}

function onSuccess()
{
// File successfully uploaded
alert("Success!");
}

function onFailure()
{
// Error occurred
alert("Request failed: " + arguments[1].get_message());
}

// Utility function to remove base64 URL prefix and store base64-encoded string in a    Uint8Array
// Courtesy: https://gist.github.com/borismus/1032746
function convertDataURIToBinary(dataURI)
{
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));

for (i = 0; i < rawLength; i++)
{
    array[i] = raw.charCodeAt(i);
}
return array;
}
  • 1
    Please add details from the link. A link only answer will be useless if the link break! – Robert Lindgren Jan 22 '14 at 18:37
  • whoops... never noticed that. – Stephen Jan 22 '14 at 19:06
  • You are not the first, nor the last, to just add a link. But from experience, it is abut dangerous and can make it hard for future readers to get a good answer. Thanks for your edit :) – Robert Lindgren Jan 22 '14 at 19:13
  • 1
    Thanks for sharing, but there is no FileAPI allowed. – Mat38 Jan 27 '14 at 19:47
  • Stephen it was really helpful thank you. Does any of you know maybe how to upload file to a particular list item ? I have also seen some solution which uses SPService library. I am wondering if it is worthy of note ? Are you guys using this class often? It seems to be much more easier in use. Can you please give me some advice because I am new in SharePoint developer world? :) Thanks in advance. – Rzodkiewka Sep 11 '14 at 16:19
3

If this is a SharePoint library the cleanest way is using the SharePoint Modal Dialog. You need your List ID and a path to the root folder.

If its an attachment you can use the AttachFile.aspx layout page. You would need the List GUID and the item ID.

This will use the out of the box SharePoint functionality and will return a status of OK if everything went okay.

var url = "siteurl/_layouts/Attachfile.aspx?ListId={" + GUID + "}&ItemId=" + ID;

    //var url = "siteurl/_layouts/Upload.aspx?List=" + listId + "&RootFolder=" + folderPath;


    var options = {
        url: url,
        dialogReturnValueCallback: function(result, fileAdded){

            if(result == SP.UI.DialogResult.OK){
                //update list of files
            }
        }
    };
    SP.UI.ModalDialog.showModalDialog(options);

You would need the list GUID and the item ID

  • This code looks very clean, but I am interested in adding an attachment to the element, not SP library. Nevertheless thanks for this sample. – Mat38 Jan 27 '14 at 19:37
  • so the url should be '/_layouts/Attachfile.aspx?ListId={GUID}&ItemId=ID' see the following link: social.msdn.microsoft.com/Forums/sharepoint/en-US/… – onzur Jan 28 '14 at 23:39
  • I edited the answer to show the change – onzur Jan 28 '14 at 23:40

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.