How to: Upload a File to a SharePoint Site from a Local Folder

Applies to: SharePoint Foundation 2010

Available in SharePoint Online

This programming task shows how to upload a file from a local folder to a folder on a Microsoft SharePoint Foundation site. The task uses the EnsureParentFolder method to ensure that the destination folder exists.

Procedures

To upload a file from a local folder to a folder on a SharePoint site

  1. Create an application page in Microsoft Visual Studio 2010, as described in Creating Application Pages for SharePoint.

  2. Add an HtmlInputFile control, a text box, a button to the form, and an FormDigest control to the page.

    <form id="Form1" method="post" runat="server">
       <SharePoint:FormDigest runat="server" />
       <input id="File1" type="file" runat="server" title="upldFileBox">
       <asp:Button id="Button1" runat="server" 
          Text="Upload File"></asp:Button>
       <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
    </form>
    
  3. In the .aspx.cs code-behind file, add using directives for the System.IO and Microsoft.SharePoint namespaces, as follows.

    Imports System.IO
    Imports Microsoft.SharePoint
    
    using System.IO;
    using Microsoft.SharePoint;
    
  4. Add the following code to the Click event for the button.

    If File1.PostedFile Is Nothing Then
        Return
    End If 
    
    Dim destUrl As String = TextBox1.Text
    
    Dim site As SPWeb = New SPSite(destUrl).OpenWeb()
    
    Dim fStream As Stream = File1.PostedFile.InputStream
    Dim contents(fStream.Length) As Byte
    
    fStream.Read(contents, 0, CInt(fStream.Length))
    fStream.Close()
    
    EnsureParentFolder(site, destUrl)
    
    site.Files.Add(destUrl, contents)
    
    if (File1.PostedFile == null)
        return;
    
    string destUrl = TextBox1.Text;
    
    SPWeb site = new SPSite(destUrl).OpenWeb();
    
    Stream fStream = File1.PostedFile.InputStream;
    byte[] contents = new byte[fStream.Length];
    
    fStream.Read(contents, 0, (int)fStream.Length);
    fStream.Close(); 
    
    EnsureParentFolder(site, destUrl);
    
    site.Files.Add(destUrl, contents);
    

    The value that you type in the text box for the destination must be an absolute URL, including the file name, which is assigned to the destUrl parameter.

    In addition to instantiating an SPWeb object for the parent site, the combined use of the SPSite constructor and OpenWeb method validates the URL and throws an argument exception if the URL is not served by the current SharePoint Foundation deployment. A HtmlInputFile object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

  5. The example defines an EnsureParentFolder method to ensure that the parent folder in the destination URL exists in the specified site, and it returns the site-relative URL of the parent folder. The EnsureParentFolder method accepts two parameters: an SPWeb object that represents the parent site, and a string that contains the absolute URL that is passed from the example’s UploadFile method. If the parent folder does not exist, the EnsureParentFolder method creates it.

    Public Function EnsureParentFolder(parentSite As SPWeb, 
            destinUrl As String) As String
    
        destinUrl = parentSite.GetFile(destinUrl).Url
    
        Dim index As Integer = destinUrl.LastIndexOf("/")
        Dim parentFolderUrl As String = String.Empty
    
        If index > - 1 Then
            parentFolderUrl = destinUrl.Substring(0, index)
            Dim parentFolder As SPFolder 
                = parentSite.GetFolder(parentFolderUrl)
    
            If Not parentFolder.Exists Then
                Dim currentFolder As SPFolder = parentSite.RootFolder
                Dim folder As String
    
                For Each folder In  parentFolderUrl.Split("/"c)
                    currentFolder = currentFolder.SubFolders.Add(folder)
                Next folder
            End If
        End If
    
        Return parentFolderUrl
    End Function 'EnsureParentFolder
    
    public string EnsureParentFolder(SPWeb parentSite, string destinUrl)
    {
        destinUrl = parentSite.GetFile(destinUrl).Url;
    
        int index = destinUrl.LastIndexOf("/");
        string parentFolderUrl = string.Empty;
    
        if (index > -1)
        {
            parentFolderUrl = destinUrl.Substring(0, index);
    
            SPFolder parentFolder 
                = parentSite.GetFolder(parentFolderUrl);
    
            if (! parentFolder.Exists)
            {
                SPFolder currentFolder = parentSite.RootFolder;
    
                foreach(string folder in parentFolderUrl.Split('/'))
                {
                    currentFolder 
                        = currentFolder.SubFolders.Add(folder);
                }
            }
        }
        return parentFolderUrl;
    }
    
  6. The GetFile method of the SPWeb class is used in combination with the Url property of the SPFile class to convert the URL to a site-relative URL, throwing an exception if the specified URL is not found within the scope of the site. The URL of the parent folder is calculated by using the String.LastIndexOf method to determine the last appearance of a forward slash (/) within the destination URL. If there is no slash (in other words, the index equals -1), then the destination is the root folder for the site and the parentFolderUrl parameter returns an empty string. Otherwise, the example uses the GetFolder method of the SPWeb class to return the destination parent folder. If the folder does not exist, the example constructs the folder.

To upload a file from a local folder that is located on the same server that is running SharePoint Foundation, you can use a FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call a custom UploadFile method, which in turn calls the previously described EnsureParentFolder method.

Public Sub UploadFile(srcUrl As String, destUrl As String)

    If Not File.Exists(srcUrl) Then

        Throw New ArgumentException(String.Format("{0} does not exist", 
            srcUrl), "srcUrl")

    End If

    Dim site As SPWeb = New SPSite(destUrl).OpenWeb()

    Dim fStream As FileStream = File.OpenRead(srcUrl)
    Dim contents(fStream.Length) As Byte
    fStream.Read(contents, 0, CInt(fStream.Length))
    fStream.Close()

    EnsureParentFolder(site, destUrl)

    site.Files.Add(destUrl, contents)

End Sub 'UploadFile
public void UploadFile(string srcUrl, string destUrl)
{
    if (! File.Exists(srcUrl))
    {
        throw new ArgumentException(String.Format("{0} does not exist", 
            srcUrl), "srcUrl");
    }

    SPWeb site = new SPSite(destUrl).OpenWeb();

    FileStream fStream = File.OpenRead(srcUrl);
    byte[] contents = new byte[fStream.Length];
    fStream.Read(contents, 0, (int)fStream.Length);
    fStream.Close(); 

    EnsureParentFolder(site, destUrl);
    site.Files.Add(destUrl, contents);
}

The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

Note

The size of the file that is uploaded cannot exceed 2 GB.

See Also

Concepts

Working with List Objects and Collections

Using Visual Studio for SharePoint Development

Security Validation and Making Posts to Update Data

Elevation of Privilege