Friday, October 11, 2013

Programmatically Upload to SharePoint Document Library

Programmatically uploading to a SharePoint Document Library seems like a simple thing, given that it's one of the more well-advertised features of SharePoint, but as it turns out, trying to craft your own from scratch is actually a bit of a challenge. I found quite a bit of documentation on how to design a method (C#), but none of them actually worked in the way I needed. All make the assumption that a static file will be uploaded, and none are designed to allow for dynamic selection of a file (Any file that will safely upload into a SharePoint document library). My intended use was to create a custom upload for use within a SharePoint form. I couldn't rely on the built in "list attachments" feature, as this breaks (And still fizzles into a spectacular wreck, I dare say - Not sure why Microsoft hasn't taken the hint from every previous version that has this flaw, which is all of them, but I'm not bitter; much) when you customize the list form.

Regardless, in the end, I had to detach the custom uploader control and method to a separate page, as I have yet been unable to determine the wrapper enveloping the control when used inside a webpart (Using the method and control inside a DataForm Web Part caused the control to be "lost" - no amount of wrapping, based on the Page, form, or webpart ID seemed to isolate the control). 

Here's my method and control that accomplished the goals (ASP.NET, Framework 3.5, C#):
<script runat="server">
public void documentUpload_OnClick(object sender, System.EventArgs e)
{       
String fileToUpload = FileUpload1.PostedFile.FileName;
String sharePointSite = "http://sharepointsite/";
String documentLibraryName = "Library Name";

using (SPSite oSite = new SPSite(sharePointSite))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
    if(FileUpload1.HasFile)
    {
    status.Text = "Uploading...";
    FileUpload1.SaveAs(FileUpload1.PostedFile.FileName);
    SPFolder myLibrary = oWeb.Folders[documentLibraryName];

      
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
        FileStream fileStream = File.OpenRead(FileUpload1.PostedFile.FileName);

        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        myLibrary.Update();
        status.Text = "Upload Complete";
        }
    }
  }
}
</script>
<asp:FileUpload runat="server" id="FileUpload1"/>
<asp:Button runat="server" OnClick="documentUpload_OnClick" Text="Upload PDF" id="Button1"/>
<asp:Label runat="server" ID="status" Text="Ready"/>

No comments:

Post a Comment