8 out of 10 rated this helpful - Rate this topic

Uploading Files to SharePoint Server 2007 from ASP.NET Web Applications by Using the HTTP PUT Method

Office 2007

Summary:  Learn how to use the HTTP PUT method to programmatically upload files from an ASP.NET Web application to a Microsoft Office SharePoint Server 2007 site. (6 printed pages)

Office Visual How To

Applies to:  Microsoft Office SharePoint Server 2007, Windows SharePoint Services 3.0, Microsoft ASP.NET, Microsoft Visual Studio 2008

Joel Krist, iSoftStone

June 2009

Overview

A common scenario involves moving files from a Microsoft ASP.NET Web application to a Microsoft Office SharePoint Server 2007 site. Office SharePoint Server provides the Copy Web service for copying files between SharePoint sites or within a SharePoint site, and the Imaging Web service for uploading files to SharePoint image libraries. However, neither Web service supports generic file uploading to SharePoint Server. This Office Visual How-To shows you how to programmatically upload files to a predefined SharePoint list by using the HTTP PUT method.

See It

Uploading Files to SharePoint Server 2007

Watch the Video

Length: 03:56 | Size: 4.87 MB | Type: WMV file

Code It | Read It | Explore It

Code It

Download the code sample that accompanies this article: Upload Files to SharePoint Server Using HTTP PUT

To demonstrate how to programmatically upload files to Office SharePoint Server 2007 from Microsoft ASP.NET applications, this section walks through the following four steps:

  1. Creating an ASP.NET Web application in Microsoft Visual Studio 2008

  2. Importing the System.IO namespace and the System.Net namespace

  3. Creating the file upload form

  4. Adding the upload code to the solution

Creating an ASP.NET Web Application in Visual Studio 2008

You can create an ASP.NET Web application by using Visual Studio 2008.

To create an ASP.NET Web application in Visual Studio 2008

  1. Start Visual Studio 2008.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Project types pane, select Visual Basic Windows or Visual C# Web type.

  4. In the Templates pane, select ASP.NET Web Application.

  5. Name the project SharePointUpload and select the Create directory for solution check box.



    Figure 1. Creating the solution

    Creating the solution
  6. Click OK.

Importing the System.IO and System.Net Namespaces

Importing the System.IO namespace and the System.Net namespace enables the sample code to work with the objects and types defined in these namespaces without needing to specify the fully qualified namespace path each time. Open the Source view of the solution's Default.aspx page and add the following @ Import directives to the top of the page, just below the @ Page directive that is created by Visual Studio.

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>

Creating the File Upload Form

For this demonstration, we use an ASP.NET Web application that consists of a single Web form that makes use of the ASP.NET FileUpload control and the Button control.



Figure 2. The ASP.NET Web form

The ASP.NET Web form

To create the Web form shown in Figure 2, open the Source view of the Default.aspx Web form that was created by Visual Studio and replace the markup located between the <body> tag and the </body> tag with the following markup.

<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" Width = "500px" />
<br />
<br />
<asp:Button ID="UploadButton" runat="server" OnClick="Button1_Click"
    Text="Upload File" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>

Adding the Upload Code to the Solution

To add the code that performs the file upload, open the Source view of the Default.aspx Web form that was created by Visual Studio, and then add the following script block between the <head> tag and the </head> tag, after the </title> tag.

<script runat="server">
            
protected void Button1_Click(object sender, EventArgs e)
{
    string uploadedFilePath = @"C:\Temp\Uploads\";
    string sharePointListPath =
        "http://<Server>/<ListName>/";
    
    if (FileUpload1.HasFile)
        try
        {
            FileUpload1.SaveAs(
                uploadedFilePath + FileUpload1.FileName);
            
            Label1.Text = "File name: " +
                 FileUpload1.PostedFile.FileName + "<br>" +
                 FileUpload1.PostedFile.ContentLength + " bytes<br>" +
                 "Content type: " +
                 FileUpload1.PostedFile.ContentType;

            UploadFileToSharePoint(
                uploadedFilePath + FileUpload1.FileName,
                sharePointListPath + FileUpload1.FileName);
        }
        catch (Exception ex)
        {
            Label1.Text = "ERROR: " + ex.Message.ToString();
        }
    else
    {
        Label1.Text = "You have not specified a file.";
    }
}

protected void UploadFileToSharePoint(string UploadedFilePath,
    string SharePointPath)
{
    WebResponse response = null;

    try
    {
        // Create a PUT Web request to upload the file.
        WebRequest request = WebRequest.Create(SharePointPath);

        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "PUT";

        // Allocate a 1 KB buffer to transfer the file contents.
        // You can adjust the buffer size as needed, depending on
        // the number and size of files being uploaded.
        byte[] buffer = new byte[1024];

        // Write the contents of the local file to the
        // request stream.
        using (Stream stream = request.GetRequestStream())
        using (FileStream fsWorkbook = File.Open(UploadedFilePath,
            FileMode.Open, FileAccess.Read))
        {
            int i = fsWorkbook.Read(buffer, 0, buffer.Length);

            while (i > 0)
            {
                stream.Write(buffer, 0, i);
                i = fsWorkbook.Read(buffer, 0, buffer.Length);
            }
        }

        // Make the PUT request.
        response = request.GetResponse();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        response.Close();
    }
}
  
</script>

This sample code assumes that the file to upload to SharePoint Server is located in the C:\Temp\Uploads folder. To change the location of the file, modify the sample code and change the value of the uploadedFilePath variable.

The code currently has a placeholder for the SharePoint site and list to upload the file to. Modify the sharePointListPath variable to specify a real SharePoint site and list.

Read It

This article provides sample code that shows how to upload a file from an ASP.NET Web application to an OfficeSharePoint Server 2007 site. The example makes use of the ASP.NET FileUpload server control to upload a file to the Web application, and then uses the HTTP PUT method to upload the file to the SharePoint site.

Explore It

  • FileUpload Class

  • WebRequest Class

  • WebRequest.Method Property

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Question to :twocoolcats
My requirement is also similar to this,could you please send the changes you made in the code for Console application. Did you overcome the error.
Question to :twocoolcats
My requirement is also similarto this,could you please send the changes you made in the code for Console application. Did you overcome the error.
Default credentials - how to specify a different credential...
I am using this method (HTTP PUT) to upload file to SharePoint in my console application and scheduled a task to run on the server.  I am getting is an error "The remote server returned an error: (401) Unauthorized." Is there a way to specify a user that have the credential on the SharePoint instead of the logged-in user (my application and SharePoint are on different servers)? $0 $0 Thanks for any help. $0Hi,$0 $0     My requirement is also similar to this,could you please send the changes you made in the code for Console application. Did you overcome the error.$0
Querry
I need to upload files from VM (and not from a local machine) to SharePoint site $0Is this suitable code for me?$0
Checkin file
The code is working for me and it uploads a text document to SP but with some errors:

Then when i attempt to open the uploaded file in SharePoint, I get this error: Some files can harm your computer. If the file information below looks suspicious, or you do not fully trust the source, do not open the file".  When i click ok on that error, I get:  "The document could not be opened for editing. A Microsoft SharePoint Foundation compatible application could not be found to edit the document."

However, I can right click on the document and say open in a new tab and it works fine. Also, when I check in the uploaded file to SP, then I can open file the with no problem.

Any ideas? I am trying to dynamically check in the file when it is uploaded to see if this resolves the issue, but I am not there yet.

Thanks
Add Meta Data
Is there any way to add properties, like Title etc when we use this PUT method?
Uploading files with special characters in the file name
This code does not work if the file name contains $ % ' + or other special characters. Any one have any idea on how to fix it?