Working with files in SharePoint from ECMA Script

Posted: Grant | Comments: 0 | May 9th, 2011
May 09

Document libraries in SharePoint are quite possibly the most common type of content on a SharePoint site. Working with documents is one of the most critical activities in any enterprise content management endeavor. With that being said, if you’re developing solutions for SharePoint; there WILL come a time when you’ll need to work with documents in libraries. While there are a few no-code ways of working with documents; handling documents has traditionally been performed from code in a Web Part, event receiver or some other custom action installed in your SharePoint farm. SharePoint 2010 offers an addition to this paradigm with the ECMA Script Library.

In my opinion, the ECMA Script Library in SharePoint is one of the most welcomed features of the product. My background is in Web application development, so I have been using AJAX technologies for quite some time. In the past, leveraging AJAX techniques from SharePoint was all on the hands of the developer. We’d have to build custom Web services to handle our actions and then consume the Web services from JavaScript. Enabling ASP.NET AJAX in SharePoint 2007 wasn’t difficult, but it had its fair share of “gotchas”. The community responded with great projects such as SPServices which is a huge step forward; but the issue remains that SharePoint needed a more AJAX centric core. With SharePoint 2010, we have it.

So how does it work? If you’ve looked at the SharePoint managed client object model or ASP.NET AJAX, you’ll already be familiar with the pattern:

  1. Requests are created using the context of the user.
  2. Queries for operations are constructed.
  3. Queries are executed asynchronously.
  4. Callback functions execute on the success or failure of the operation.

So let’s look at an example:

I need a JavaScript function that will copy a file from a source URL to a destination URL. The source file is in the current site that the user will be browsing. I want the file to be overwritten if it already exists.

Using the ECMA Script Library we can accomplish this goal:

/// <reference path="D:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\MicrosoftAjax.js" />
/// <reference path="D:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.js" />
/// <reference path="D:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.Core.js" />
function copyFile(sourceUrl, destinationUrl) {
    var ctx, file, notifyId;

    ctx = SP.ClientContext.get_current();

    file = ctx.get_web().getFileByServerRelativeUrl(sourceUrl);
    ctx.load(file);

    // Set a notification to the user that we are going to copy the file.
    notifyId = SP.UI.Notify.addNotification('Copying file...', true);

    ctx.executeQueryAsync(
        function (sender, args) {
            // File loaded. Now we want to copy the file. We'll use a nested AJAX call
            file.copyTo(destinationUrl, true);

            ctx.executeQueryAsync(
                function (sender, args) {
                    // File copied successfully!
                    SP.UI.Notify.removeNotification(notifyId);

                    // Let the user know that the operation was successful
                    SP.UI.Notify.addNotification('File copied successfully', false);
                },
                function (sender, args) {
                    // Unable to copy file.
                    SP.UI.Notify.removeNotification(notifyId);

                    showError(args.get_message());
                });
        },
        function (sender, args) {
            // Unable to locate file.
            SP.UI.Notify.removeNotification(notifyId);

            showError(args.get_message());
        });
}
function showError(msg) {
    var statusId;

    statusId = SP.UI.Status.addStatus('File Copy Error:', msg);
    SP.UI.Status.setStatusPriColor(statusId, 'red');

    // Remove the error message after 5 seconds
    window.setInterval(function(){SP.UI.Status.removeStatus(statusId);}, 5000);
}

That code sample is a bit lengthy, but you can see that we can use the ECMA Script Library to create a reusable JavaScript function to work with files; and this is just the tip of the iceberg. We can then use jQuery or some other means to invoke this function from a click handler. The result; file management operations in SharePoint entirely from JavaScript. Truly wonderful….

Leave a Comment