Sign up ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I want to upload a word document to sharepoint document library using javascript (say for ex .Net site).

How can i achieve this?

share|improve this question
    
@AmalHashim I am new to Sharepoint, don't have idea how to achieve this –  User5590 Apr 27 at 12:01
    
In order to use JavaScript Client Object Model you need all JS files. These files reside in SharePoint server. So I don't think you can use it outside SharePoint. You can use SharePoint .Net Client Object Model I think. –  Amal Hashim Apr 27 at 12:02
    
@AmalHashim Can't i just copy all required js to my application, and then use javascript code to do this? –  User5590 Apr 27 at 12:03
    
Is this useful - msdn.microsoft.com/EN-US/library/office/dn769086.aspx ? –  User5590 Apr 27 at 12:05
    
@AmalHashim is correct, Sharepoint Client Object Model will be a good choice for you in this case –  Ransher Singh Apr 27 at 14:40

2 Answers 2

SharePoint 2013 provides a new client object model that enables you to create SharePoint solutions that run remotely from the SharePoint server farm. For example, the client object model enables you to consume and manipulate SharePoint data in Windows Forms applications, WPF application, console applications, Silverlight applications, and ASP.NET Web applications.

What you will need to do to achieve this is make references to the Sharepoint client object model libraries namely Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll from within your asp.net project.

Connecting remotely to the Sharepoint site will be achieved through SPClientContext

SPClientContext = new ClientContext(SP_URL); //SP_URL is your share point site URL
SPClientContext.Credentials =new NetworkCredential(SPUserName, SPPassWord, SPDomainName);
var SPWeb = SPClientContext.Web;
SPClientContext.Load(SPWeb);

Uploading the file remotely will use the SaveBinaryDirect() method of File object

public string UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)
    {
        string sDocName = string.Empty;
        try
        {
            if (SPWeb != null)
            {
                var sFileUrl = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);
                sDocName = sFileName;
            }
        }
        catch (Exception ex)
        {
            sDocName = string.Empty;
            SPErrorMsg = ex.Message;
        }
        return sDocName;
    }

See more at: http://www.ecanarys.com/blog-entry/how-upload-documents-sharepoint-2013

share|improve this answer

It's still quite uncomfortable to upload documents by using the JSOM API. But it's possible.

In your case your Word file must be not larger than 1.5 MB. Additionally the clients browser must support HTML5.

Here is a code example (it references also the jQuery library):

$(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;
}

When you work with larger files you must use the REST API following by MSDN.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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