Uploading a file in SharePoint

Uploading a file from your hard disk to a site in SharePoint

Download application and source code

Use the browse button to find a file on your hard disk. Destination contains the URL of the SharePoint site where you want to upload the file. Complete URL must be written in the Destination box, for example, "http://mainportal/sites/site1". Destination can contain anything from a site to document library. Suppose you want to upload a file to a document library which is part of the site "site1" above then Destination box would contain: "http://mainportal/sites/site1/doclib". Here doclib is the name of the document library. Clicking the Upload button will show you the status of the operation. Large files may take few seconds to upload.

Here is the code:

Public Function UploadFile() As Boolean

Try

       Dim Site As SPWeb = New SPSite(TextBox2.Text).OpenWeb

       Dim fStream As FileStream = System.IO.File.OpenRead(TextBox1.Text)
       Dim Contents(CInt(fStream.Length)) As Byte

       fStream.Read(Contents, 0, CInt(fStream.Length))

       EnsureParentFolder(Site, TextBox2.Text)

       Site.Files.Add(TextBox2.Text & "/" & Microsoft.VisualBasic.Mid(TextBox1.Text, 4), Contents)

       Return True

Catch Ex As Exception
       MsgBox(Ex.Message)

End Try

End Function
 

This function uploads the file. Code for EnsureParentFolder() is shown below:

Public Function EnsureParentFolder(ByVal ParentSite As SPWeb, ByVal Destination As String) As String

Destination = ParentSite.GetFile(Destination).Url

Dim index As Integer = Destination.LastIndexOf("/")
Dim ParentFolderURL As String = String.Empty

If index > -1 Then

ParentFolderURL = Destination.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

 

The EnsureParentFolder method ensures that the parent folder in the destination URL exists in the specified site, and it returns the site-relative URL of the parent folder.

For more help, see SPS SDK that can be downloaded from the Microsoft site.

-SSA