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 8 and 2 and type the answer here:
  • Post
  • Free SharePoint Web Parts (3rd Party) Konrad Brunner - UGS&#39;s Web Parts (broken link 8/25) Document

  • Hi everyone,

    I've been struggling for some days now trying to get this working on a secured SharePoint Server 2003. Here's the solution that worked for me.

    1) Change the credentials in the helperclass:

      service.Credentials = new NetworkCredential("username", "password");

    2) In the web.config file on the server change the trustlevel to:

      <trust level="WSS_Medium" originUrl=".*" />

    Just wanting to share this with you guys, might help you out.

  • When i browse the SPFiles.asmx from IIS

    I get the error

    Could not create type  WSCheckOut.SPFiles

  • MOSS 2007

    I am trying to Check in a document after Editing its properties and get the following error :

    Value does not fall within the expected range

  • Erika,

    I used your file upload sample and followed your instructions for installation.

    I run sharepoint on port 81.

    This is the code I use to upload a generated excel document.

               WSS_UPLOAD.SPFiles SharePointUploadService = new global::EXCELconnector.WSS_UPLOAD.SPFiles();

               SharePointUploadService.Url = "http://10.0.0.11:81/_vti_bin/SPFiles.asmx";

              SharePointUploadService.PreAuthenticate = true;

              SharePointUploadService.Credentials = new System.Net.NetworkCredential("administrator", "1616xn152", "mammoth");

              System.IO.FileStream fStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open);

              byte[] binFile = new byte[(int)fStream.Length];

              fStream.Read(binFile, 0, (int)fStream.Length);

              fStream.Close();

              SharePointUploadService.UploadDocument(fileName, binFile, "Cherubim", null);

    On the UploadDocument call I receive the following exception:

    System.Web.Services.Protocols.SoapException was unhandled

     Message="Server was unable to process request. ---> Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed."

     Source="System.Web.Services"

     Actor=""

     Lang=""

     Node=""

     Role=""

     StackTrace:

          at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)

          at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)

          at EXCELconnector.WSS_UPLOAD.SPFiles.UploadDocument(String fileName, Byte[] fileContents, String targetFolder, String targetWebSiteOverride)

          at EXCELconnector.EXCELsink.PutRow(XmlNode row)

          at CherubimExchange.processSequence.Execute() in C:\Prisma.Expirimenten.dotnet2\CherubimExchangeService\CherubimSourceConnector\HeartBeat.cs:line 144

          at CherubimExchange.TaskDef.Execute() in C:\Prisma.Expirimenten.dotnet2\CherubimExchangeService\CherubimSourceConnector\TaskDef.cs:line 25

          at CherubimExchange.TaskDef.TaskDefCallBack(Object stateInfo) in C:\Prisma.Expirimenten.dotnet2\CherubimExchangeService\CherubimSourceConnector\TaskDef.cs:line 134

          at System.Threading._TimerCallback.TimerCallback_Context(Object state)

          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

          at System.Threading._TimerCallback.PerformTimerCallback(Object state)

    Any clue?

  • Jan,

    Were you able to solve the security issue? I am facing the same issue. Please help if you have solution.

  • Getting the error: "Value does not fall within the expected range.Microsoft.SharePoint"

    void UploadFilesToSharepoint(HttpFileCollection files)

    {

    uploadservice = new Uploadwebsrv.SPUploadFiles();

    uploadservice.PreAuthenticate = true;

    uploadservice.Credentials = GetNetworkCredential();

    uploadservice.Timeout = 1000000;

    for(int i=0; i<files.Count; i++)

    {

    string fileName = Path.GetFileName(files[i].FileName);

    Stream fstream = files[i].InputStream;

    byte[] fbytes = new byte[fstream.Length];

    fstream.Read(fbytes, 0, fbytes.Length);

    fstream.Close();

    targetFolderPath = ConfigurationSettings.AppSettings["TargetFolder"].ToString();

    try

    {

    if (fileName!=null && fileName.Length>0)

    {

    string result = uploadservice.UploadDocument(fileName,fbytes,targetFolderPath);

    }

    }

    catch (Exception ex)

    {

    //LogMessages(MessageType.Exception, ex.ToString(), "TotalFiles:" + files.Count.ToString());

    }

    }

    }

    any ideas?

  • When I am Running this whole webservice with the class i am getting a error that "Access to the path "F:\task\ExpensesGourav.txt" is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String str) at System.IO.FileStream" the path it is showing is the one from where i want to upload the file..

    please tell me the solution asap.....

  • For an example of uploading via FrontPage RPCs please see http://www.benherman.com/ftp/copy-sp.ps1.

    Ben

Page 5 of 5 (69 items) 12345