Wednesday, April 9, 2008

Attaching Files to a SharePoint List using SharePoint Web Services and a FileUpload control.

Uploading and attaching a file to a SharePoint List using SharePoint web Services is a fairly easy task.

There are several ways to accomplish this. In this example we are going attach a file to a list Item which already exists.

Each list item has and Id associated with it. There is an ID and a Unique Id. The ID is a simple integer value where the Unique Id is a GUID. We simply need to get the integer ID in order to attach a file to the list item.

Here we simple add the file upload control to the front end.

<asp:FileUpload ID="fileUpload_Resume" runat="server"/>

First, find the Id of the list item that you will be attaching a file to. This can be done at the moment you add the list item to the List by parsing the XMLNode that comes back from the Update function you used to add the item to the list

XmlNode returnedXml = theList.UpdateListItems("listName",

batch_element);
XmlNode IdNode = returnedXml.ChildNodes[0].ChildNodes[2];
String listItemId = IdNode.Attributes["ows_ID"].Value;

Note: The above method assumes that you've add only one item to the list.

Next, we will want to test to make sure that a file was uploaded.

if (fileUpload_Resume.PostedFile != null){

'listId is the guid of the list.
uploadAttachment(listId, fileUpload_Resume, listItemId);

}

Finally, here is the function for uploadAttachment:


public void uploadAttachment(String listName,
FileUpload fUploadControl,
String listItemId){
try{

if (fUploadControl.PostedFile != null){

theList.Lists consultantList = new wsConsultantsList.Lists();

theList.CookieContainer = _cookieJar;

theList.Url = "http://server.com/listName/_VTI_BIN/lists.asmx";

Stream fs = fUploadControl.PostedFile.InputStream;
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, (int)fs.Length);
fs.Close();

// Add the file to the ListItem as an Attachment
theList.AddAttachment(listName, listItemId, fUploadControl.FileName, fileContents);
}
}catch (Exception ex){
string err = ex.Message;
}
}

We just set our Cookie Container, get the contents of the file, add the attachement with the SharePoint Lists web service.

For more information on how to access sharepoint lists and inserting list items, visit Brian Cordell's blog on SharePoint WebServices at http://sophicgroupmicrosoft.blogspot.com/

If you have any questions, feel free to contact me at heeter.david@sophicgroup.net