The client object Model (COM) is introduced in Sharepoint2010 to enhance external access to SharePoint site information (sharepoint2007 only through Web service)
There are 3 types of client object models in SharePoint:
- ECMAScript
- . NET managed Client Object model
- Silverlight Client Object Model
There are 3 client object models that use CLIENT.SVC to interact with the server, and for COM do not elaborate here, the learning objective in this section is to upload attachments through the client object model
The containers that SharePoint often uses to store attachments are:Library and list, which is the first feature to be implemented in the list to implement storage attachments.
- List setting-->advanced settings-->attachment Enabled
- Create a new console/winform program
- Adding references to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll
using(varClientContext =Newclientcontext (URL)) {Clientcontext.credentials=creds; using(varFS =NewFileStream (FileName, FileMode.Open)) { varfi =NewFileInfo (fileName); varList =ClientContext.Web.Lists.GetByTitle (ListTitle); Clientcontext.load (list. RootFolder); Clientcontext.executequery (); //Upload attachments to list stringAttachmenturl = list. Rootfolder.serverrelativeurl +"/attachments/"+ itemid.tostring () +"/"+fi. Name; //upload attachments to library stringAttachmenturl = list. Rootfolder.serverrelativeurl +"/"+fi. Name; Microsoft.SharePoint.Client.File. Savebinarydirect (ClientContext, Attachmenturl, FS,true);
}}
Note : The above code uploads attachments to the library and list ( already exists/attachments/itemid/folder) without any problems, but if uploading attachments to a new list item will be reported 409 server-Rejected errors
The reason is because the new list item does not have a folder like/attachments/itemid, and the workaround is to upload the attachment via a Web service.
- Web Service Upload Attachments
var New listsservice.lists (); = creds; " /_vti_bin/lists.asmx " ; return soapclient.addattachment (ListName, ItemId, Path.getfilename (fileName), System.IO.File. ReadAllBytes(FileName));
Summary: This section describes how to upload attachments through COM, and also provides a different way to upload attachments (Web service).
SharePoint Client object model upload attachments