Erika Ehrli - Adventures with Office Products & Technologies
MSDN & TechNet: Releasing Office, SharePoint, Exchange & Lync Centers and content for developers and IT professionals.

How to: Magic with SharePoint 2003, uploading files using a Web service

How to: Magic with SharePoint 2003, uploading files using a Web service

Rate This
  • Comments 69

Some time ago I blogged about my intentions of uploading files to a SharePoint Document Library site from a local folder using some kind of Web service. After doing some research and some tests, I found a very easy way to do that and now I want to share with you the approach I followed since you might find it useful as well.

Prerequisites

To build this solution, you need to install Office SharePoint Portal Server 2003 and follow the next steps:

  • Create a Document Library
  • Grant access to the users that will upload files to the Document Library:

To install the Web service:

  1. Download ODC_WritingCustomWebServicesSampleSPPT.EXE.
  2. Extract the download contents to your hard drive and Run build.bat.
    • Note: This will install the Web service on the _vti_bin virtual directory inside the Default Web Site.
  3. Open the IIS Management Console (INETMGR) and navigate to the the _vti_bin virtual directory (inside the Default Web Site).
  4. Find SPFiles.asmx, right click, and Browse.
  5. Navigate to http://localhost/_vti_bin/SPFiles.asmx to validate if you have installed successfully the Web Service.

To consume the Web Service:

  1. From your managed application, add a reference to the http://localhost/_vti_bin/SPFiles.asmx Web Service.
  2. Call the Web service DocumentLoader
  3. Create a helper class to upload files. You can use the helper class I created.
    using System;
    using 
    System.Net;
    using 
    System.IO;
    using 
    System.Configuration;
    using 
    System.Text;
    using 
    System.Web;
    using 
    System.Security;
    using 
    System.Web.Security;
    using 
    System.Web.UI;
    using 
    System.Web.UI.WebControls;
    using 
    System.Web.UI.WebControls.WebParts;
    using 
    System.Web.UI.HtmlControls;
    using 
    DocumentLoader;

    /// <summary>
    /// A sample SharePointHelper class to upload files
    /// </summary>
    public class SharePointUploadHelper {
       
    private string _sharepointDocumentLibrary;

       public 
    SharePointUploadHelper() {
          _sharepointDocumentLibrary 
    ConfigurationManager.AppSettings["SharePointDocLibrary"];
       
    }

       
    public string UploadDocumentsToSharePoint(string fileName) {

          DocumentLoader.SPFiles svcDocLoader 
    = new DocumentLoader.SPFiles();
          
    svcDocLoader.PreAuthenticate = true;
          
    svcDocLoader.Credentials CredentialCache.DefaultCredentials;

          string 
    strPath fileName;
          string 
    strFile strPath.Substring(strPath.LastIndexOf("\\") + 1);
          string 
    strDestination _sharepointDocumentLibrary;

          
    FileStream fStream = new FileStream(strPath, System.IO.FileMode.Open);
          byte
    [] binFile = new byte[(int)fStream.Length];
          
    fStream.Read(binFile, 0, (int)fStream.Length);
          
    fStream.Close();
          string 
    result svcDocLoader.UploadDocument(strFile, binFile, strDestination);

          return 
    (result);
       
    }
    }
  4. Create a Web Form, Win Form, or console application that will require a user to upload files.
     
  5. Call the UploadDocumentsToSharePoint method of the SharePointUploadHelper class, for example:
    protected void btnLoadFile_Click(object sender, EventArgs e)
        {
            SharePointUploadHelper fh 
    = new SharePointUploadHelper();
            string 
    serverTempFilePath Server.MapPath(@"/yourApplication");
            
    contentFileUpload.PostedFile.SaveAs(serverTempFilePath);
            
    lblUploadResults.Text fh.UploadDocumentsToSharePoint(serverTempFilePath);
        
    }
  6. Open the configuration file (i.e. Web.config) and turn on impersonation.
    <identity impersonate="true" />
  7. Add a configuration key that points to the SharePoint Document Library where you will upload files.
    <add key="SharePointDocLibrary" value="http://myServerName/myDocumentLibrary"/>
  8. Build your application
  9. Run and test the application, and there, a great web service.

I can tell you it works, just keep in mind the download is a code sample.

Enjoy!

-Erika

Leave a Comment
  • Please add 5 and 1 and type the answer here:
  • Post
  • Is this method appropriate for uploading large files (>20MB) into a Sharepoint DL?  I have tried this but do not think a web service is appropriate for large file uploads.  I think FTP would be better (but obviously you cannot use it to upload to a Sharepoint DL).
  • Hi Tim,

    You might explore other alternatives if you plan to upload big files (>20MB). The biggest file I have uploaded using this Web service is about 2 MB.

    You know best practices are sometimes subjective, but I know that users should not upload files bigger than 2 MB while using a File Upload service. IIS and ASP.NET have a file size limitation.

    One thing you can do to upload bigger files, is modify the httRuntime maxRequestLength value inside your web.config file. For example, if you add this line of code...

    <httpRuntime maxRequestLength="8192"/>

    to your Web.config file, you would allow users to upload files with a max length of 8 MB.

    I hope this helps...
    -Erika
  • The non-technical people may find WISDOM Explorer part of WISDOM Document Management Framework works well with the larger files.
    It also prompts for meta tags etc
  • Thanks Erika.  Great hint.

    And in VP.net, that would be:

      Public Function UploadDocumentsToSharePoint(ByVal fileName As String) As String

         Dim svcDocLoader As DocumentLoader.SPFiles =  New DocumentLoader.SPFiles()
         svcDocLoader.PreAuthenticate = True
         svcDocLoader.Credentials = CredentialCache.DefaultCredentials

         Dim strPath As String =  fileName
         Dim strFile As String =  strPath.Substring(strPath.LastIndexOf("\\") + 1)
         Dim strDestination As String =  _sharepointDocumentLibrary

         Dim fStream As FileStream =  New FileStream(strPath,System.IO.FileMode.Open)
         Dim binFile() As Byte =  New Byte(CType(fStream.Length) {}, __0__)
         fStream.Read(binFile, 0, CType(fStream.Length, Integer))
         fStream.Close()
         Dim result As String =  svcDocLoader.UploadDocument(strFile,binFile,strDestination)

         Return (result)
      End Function
  • Erika,

    I've tried to modify the code to use a string instead of a file.  I'm getting
    "Value does not fall within the expected range.Microsoft.SharePoint"

    Any ideas, or info on getting more about the error that's occuring?

    Thanks in advance...

    /bac


       <WebMethod(Description:="Upload a file to a doc lib.  The web service App Setting SharePointDocLibrary sets the destination library.")> _
       Public Function UploadDocumentToSharePoint(ByVal asDocName As String, ByVal asdocumentContents As String) As String
           ' 20060601 R.Chauvin bob_chauvin@yahoo.com
           ' adapted from http://blogs.msdn.com/erikaehrli/archive/2006/05/04/SharePointUploadHelper.aspx?CommentPosted=true#commentmessage
           Dim svcDocLoader As DocumentLoader.SPFiles = New DocumentLoader.SPFiles()
           svcDocLoader.PreAuthenticate = True
           svcDocLoader.Credentials = CredentialCache.DefaultCredentials

           'Dim strPath As String = asdocumentContents
           'Dim strFile As String = strPath.Substring(strPath.LastIndexOf("\\") + 1)
           Dim strDestination As String = _sharepointDocumentLibrary

           'Dim fStream As FileStream = New FileStream(strPath, System.IO.FileMode.Open)
           'Dim binFilex() As [Byte] = New Byte(CType(fStream.Length, Integer)) {}
           Dim binFile() As [Byte] = System.Text.Encoding.UTF8.GetBytes(asdocumentContents)
           'fStream.Read(binFile, 0, CType(fStream.Length, Integer))
           'fStream.Close()
           Dim result As String = svcDocLoader.UploadDocument(asDocName, binFile, strDestination)

           Return (result)
       End Function
  • Interesting... If I use
    http://localhost/my site/forms/ I get a different error
    "The folder that would hold URL 'Enterprise Contact Cleanup Form/Forms/' does not exist on the server.Microsoft.SharePoint"
  • Found the issue...  My url had a trailing /.  Removed that, and it worked for either localhost or server name.

    Sorry:)
  • A simplified VB version that takes string as file contents.

       Public Function UploadDocumentToSharePoint(ByVal asDocName As String, ByVal asdocumentContents As String) As String
           ' 20060601 R.Chauvin bob_chauvin@yahoo.com
           ' adapted from http://blogs.msdn.com/erikaehrli/archive/2006/05/04/SharePointUploadHelper.aspx?CommentPosted=true#commentmessage
           Dim svcDocLoader As DocumentLoader.SPFiles = New DocumentLoader.SPFiles()
           svcDocLoader.PreAuthenticate = True
           svcDocLoader.Credentials = CredentialCache.DefaultCredentials

           'Dim strPath As String = asdocumentContents
           'Dim strFile As String = strPath.Substring(strPath.LastIndexOf("\\") + 1)
           Dim strDestination As String = _sharepointDocumentLibrary

           Dim binFile() As [Byte] = System.Text.Encoding.UTF8.GetBytes(asdocumentContents)

           'Dim fStream As FileStream = New FileStream("c:\temp\ASPNETSetup_00000.log", System.IO.FileMode.Open)
           'Dim binFilex() As [Byte] = New Byte(CType(fStream.Length, Integer)) {}
           'fStream.Read(binFilex, 0, CType(fStream.Length, Integer))
           'fStream.Close()
           Dim result As String = svcDocLoader.UploadDocument(asDocName, binFile, strDestination)

           Return (result)
       End Function

  • I am getting the following error: "The folder that would hold URL 'sites/projects/myproject/project%documents/forms' does not exist on the server.Microsoft.SharePoint". i have given the following key in web.config file. "http://myserver/sites/projects/myproject/Project%20Documents/forms"
  • Would it be possible to upload a file overwriting the existing one and thus mantaining the versioning?

    Thanks in advance
  • A new error:

    The folder that would hold URL 'sites/EntContacts/shared documents' does not exist on the server.Microsoft.SharePoint"
  • Bob and Karthik,

    I remember getting this error too. I am using a document library on the default site:

    <add key="SharePointDocLibrary" value="http://myserver/myDocLibrary"/>

    I have not tried using the service with document libraries inside sites, let me run some tests and I will let you know if I was able to make this work.
  • Thanks Erika,

    Yes, I created a form lib off the default site and it works, but not off sub site doc libs.

    Also,  Any idea as to wether this will work with V3?
  • And as CNatra asked, How can we handle versions?  I'll experiment with check out/in, but if you (Erika) know better.

    Or, can we get the source to the .dll and extend it?
  • Another interesting blog with some hints...

    http://www.sharepointblogs.com/rcragg/archive/2004/05/25/482.aspx
Page 1 of 5 (69 items) 12345