Skip to content

Uploadify for SharePoint

May 25, 2011

Uploadify is a jQuery plugin that integrates a fully-customizable multiple file upload utility on your website. It uses a mixture of Javascript, ActionScript, and any server-side language to dynamically create an instance over any DOM element on a page.

The jQuery Uploadify website gives us ready example for PHP, but leaves us clueless on how to implement the same in .NET or even in SharePoint

So, here I am presenting you with example of C# for SharePoint implementation (upload.ashx) for the jQuery Uploadify plugin.

How to add it to SharePoint

  • Download the latest stable version of Uploadify
  • Extract everything to a desktop folder
  • Create a new SharePoint Empty Project
  • Add a new Visual Web Part
  • Add the SharePoint “Layouts” Mapped folder
  • Add all uploadify extracted files to this folder, except the php files
  • Add the following source code to you user control
    <script src="/_layouts/Uploadify/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="/_layouts/Uploadify/jquery.uploadify.v2.1.4.js" type="text/javascript"></script>
    <script src="/_layouts/Uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
    <script src="/_layouts/Uploadify/swfobject.js" type="text/javascript"></script>
    <link href="/_layouts/Uploadify/uploadify.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        // <'[CDATA[
        $(document).ready(function () {
            $("#fileInput").uploadify({
                'uploader': '/_layouts/Uploadify/uploadify.swf',
                'cancelImg': '/_layouts/Uploadify/cancel.png',
                'buttonText': 'Browse Files',
                'script': '/_layouts/Uploadify/Upload.ashx',
                'scriptData': {  },
                'fileDesc': 'Document Files',
                'fileExt': '*.doc;*.docx;*.pdf',
                'multi': true,
                'auto': true,
                'queueSizeLimit': 5,
                'sizeLimit': 4000000,
                'folder': '/uploads',
                'onAllComplete': function (event, queueID, fileObj, response, data) {
                    alert(response);
                }
            });
        });
        // ]]
    </script>
    
    <input id="fileInput" name="fileInput" type="file" />
    
  • Create a new ashx file in SharePoint “Layouts” Mapped Folder named Upload.ashx
    <%@ Assembly Name="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ WebHandler Language="C#" Class="Upload" %>
    
    using System;
    using System.Web;
    using Microsoft.SharePoint;
    using System.IO;
    using System.Collections;
    
    public class Upload : IHttpHandler
    {
    /// <summary>
    /// You will need to configure this handler in the web.config file of your
    /// web and register it with IIS before being able to use it. For more information
    /// see the following link: http://go.microsoft.com/?linkid=8101007
    /// </summary>
    #region IHttpHandler Members
    
    public bool IsReusable
    {
    // Return false in case your Managed Handler cannot be reused for another request.
    // Usually this would be false in case you have some state information preserved per request.
    get { return false; }
    }
    
    public void ProcessRequest(HttpContext context)
    {
    try
    {
    string result = "success";
    HttpPostedFile hfc = context.Request.Files["Filedata"];
    
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
    {
    using (SPWeb objSPWeb = objSPSite.OpenWeb())
    {
    SPFolder myLibrary = objSPWeb.Folders["Documents"];
    
    if (myLibrary != null)
    {
    objSPWeb.AllowUnsafeUpdates = true;
    //Add a new item
    
    // Prepare to upload
    Boolean replaceExistingFiles = false;
    
    string file_name = Path.GetFileName(hfc.FileName);
    byte[] file_content = new byte[Convert.ToInt32(hfc.ContentLength)];
    hfc.InputStream.Read(file_content, 0, Convert.ToInt32(hfc.InputStream.Length));
    
    // Upload document
    SPFile spfile = myLibrary.Files.Add(file_name, file_content, replaceExistingFiles);
    
    // Commit
    myLibrary.Update();
    
    objSPWeb.AllowUnsafeUpdates = false;
    
    }
    }
    }
    });
    
    context.Response.ContentType = "text/plain";
    context.Response.Write(result);
    }
    catch (Exception ex)
    {
    context.Response.ContentType = "text/plain";
    context.Response.Write("Error: " + ex.Message);
    
    }
    }
    
    #endregion
    }
    

And that’s it! 🙂

I did this with the help of this Video Tutorial by Cason Clagg.

Advertisements

From → SharePoint 2010

10 Comments
  1. nonoxp permalink

    Hi,
    I’m having trouble understanding the link between the folder property defined in the javascript object and the Documents folder you call in the handler. Did you have to create an “upload” folder somewhere on the server ?

    • Hi,

      In fact, there’s no link between the folder property defined on the JS object and the Documents folder on the handler. That was a piece of code that I left from the Cason Cragg script, I think you can delete it.

      • nonoxp permalink

        Ok thanks man, so it’s all about the handler.
        Actually it’s triggering ntlm authentification and I don’t have a clue why (running under /sites/xxx url header).
        I’ll try later to do a code behind version and a step-by-step debug to figure it out.

      • I’ll try to get some time today to check that NTLM auth problem. If you find any problem on my code, please, let me know.

        Thanks.

      • nonoxp permalink

        Well, I’m just having http 401 then some timeouts leading to 404 and even some 410, even locally, even with farm admin account.
        I didn’t try to play with security levels or auth. methods but I’ve solved my upload problem with DAV mapping. Enough time on this handler 😥

        Thanks by the way.

  2. Every file upload handler I’ve seen created for SharePoint hard-codes the Document Library that the file is uploaded to. How hard would it be to include a query string, or some other parameter to specify a library before upload?

    • I think it won’t be that hard. It’s just a matter of having a textbox or a dropdown to ser the folder and on the source code sede se need to use this new variable.

      I’m going to make this change next week.

  3. Vishal permalink

    Hi,

    I have done exactly what you have explained above. But, somehow its not working for me.

    It is just showing me the Upload Files button. But when I click it, nothing happens.

    I checked this in Firefox, Chrome and IE9. Same issue everywhere.

    Please Help!

  4. Vishal permalink

    Adding to my comment above: There is no javascript error shown by the browser.

    So, is my Handler (Upload.ashx) code throwing some errors?

    • I’m having a lot of work, I’m trying to find some time to update this feature and help you next week.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: