Friday, June 6, 2008

Upload File to SharePoint Document Library Using the ASP.NET FileUpload Control

Recently I needed to create a Web Part that included the following:

  • A Master / DetailsView form that integrates with an external database.
  • A way to show existing documents and add new documents (and column metadata) to an existing SharePoint Document Library.

After some research I figured out how to do this by converting the FileUpload control and a ASP.NET Button control which does the actual uploading. In a nutshell you convert the posted file to a byte array and then use the SharePoint OM to upload the file. I have included the following functionality:

  • Overwrite File - You have the option of overwriting existing files or creating a new version if you have versioning turned on for the Document Library. 
  • Include Subfolders - This is done by passing a slash delimited string relative to the Document Library.
  • Update Column Metadata - This is done by passing a Dictionary<string, string> object that includes a key which is the column name and value as the value.

There is a probably a little more work I need to do to make this more bullet-proof, but it should give you a start. You can also combine it to do multiple files using my previous post: Upload Multiple Files With ASP.NET. Note: I have abbreviated the code below for brevity.

ASP.NET

<asp:FileUpload ID="fileBrowse" runat="server" />
<asp:Button ID="fileUpload" runat="server" Text="Upload Files" OnClick="fileUpload_Click" />

Code Behind:

protected void fileUpload_Click(object sender, EventArgs e)
{
    if (fileBrowse.PostedFile != null)
    {
        string siteUrl = @"http://myportal/teamsite";
        string docLibraryName = "Shared Documents";
        string folderPath = "2008/01";
        string fileName = Path.GetFileName(fileBrowse.PostedFile.FileName);
        byte[] fileBytes = GetFileBytes();
        Dictionary<string, string> columnValues = new Dictionary<string, string>();
        columnValues.Add("Document Type", "Financial");
        columnValues.Add("Author", "Mr. Burns");
        UploadFile(siteUrl, docLibraryName, folderPath, fileName, fileBytes, columnValues, true);
    }
}

public byte[] GetFileBytes()
{
    Stream stream = fileBrowse.PostedFile.InputStream;
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, (int)stream.Length);
    stream.Close();
    return bytes;
}

public void UploadFile(string siteUrl, string docLibraryName, string folderPath,
    string fileName, byte[] fileByteArray, Dictionary<string, string> columnValues, bool overWrite)
{
    try
    {
        string fileUrl = siteUrl.EnsureEndSlash() + docLibraryName.EnsureEndSlash() +
            folderPath.EnsureEndSlash() + fileName;
        string currentFolder = siteUrl.EnsureEndSlash() + docLibraryName.EnsureEndSlash();
        using (SPWeb web = new SPSite(siteUrl).OpenWeb())
        {
            web.AllowUnsafeUpdates = true;
            SPFolder folder = web.Folders[docLibraryName];
            if (folderPath != string.Empty)
            {
                foreach (string subFolder in folderPath.Split('/'))
                {
                    currentFolder = currentFolder.EnsureEndSlash() + subFolder;
                    if (!web.GetFolder(currentFolder).Exists)
                    {
                        folder.SubFolders.Add(subFolder);
                    }
                    folder = folder.SubFolders[subFolder];
                }
            }
            if (overWrite || !web.GetFile(fileUrl).Exists)
            {
                folder.Files.Add(fileName, fileByteArray, true);
            }
            else
            {
                folder.Files[fileName].CheckOut();
                folder.Files.Add(fileName, fileByteArray, true);
                folder.Files[fileName].CheckIn(String.Empty);
            }
            SPFile file = folder.Files[fileUrl];
            foreach (KeyValuePair<string, string> columnValue in columnValues)
            {
                file.Item.Properties[columnValue.Key] = columnValue.Value;
            }
            file.Item.Update();
        }
    }
    catch (Exception ex)
    {
        //TODO: Add Exception Handling
    }
}

5 comments:

  1. Great tutorial.... This tips is very helpfull, thanks for sharing this valuable information.


    Regards,

    SharePoint Hosting Provider
    http://www.asphostportal.com

    ReplyDelete
  2. EnsureEndSlash()doesnt have body..... pls provide

    ReplyDelete
  3. a very ragged EnsureEndSlash()

    public static string EnsureEndSlash(this string input)
    {
    if (string.IsNullOrEmpty(input))
    {
    return input;
    }

    return input + input.EndsWith("/") ? string.Empty : "/";
    }

    ReplyDelete