Today I came across the need to be able to upload documents to a SharePoint list. Not so bad, I have done this before, but this time I also need to populate some custom metadata about the document. After a lot of looking, searching and exceptions I finally found the answer and here it is.
Add References to Microsoft.SharePoint.Client Library
Install-Package Microsoft.SharePoint.Client
Define a form
The important part I always forget is the enctype=”multipart/form-data”.
1: <form id="formUpload" method="POST" enctype="multipart/form-data ">
2: <input type="file" id="fileUpload" name="fileUpload" runat="server"/>
3: <input type="submit" value="upload"
4: OnServerClick="btnUploadTheFile_Click" runat="server"/>
5: </form>
The btnUploadTheFile_Click Handler
1: private void UpLoadToSharePoint()
2: {
3: var fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
4: var fileStream = new FileStream(fileUpload.PostedFile.FileName, FileMode.Open);
5: var byteStream = new byte[fileStream.Length];
6: fileStream.Read(byteStream, 0, byteStream.Length);
7:
8: var serverRelativeUrl = "/MySite/MyDocumentLibrary/" + fileName;
9:
10: var fileCreationInformation = new FileCreationInformation
11: {
12: Content = byteStream,
13: Overwrite = true,
14: Url = serverRelativeUrl
15: };
16:
17: var file = _sharePointList.RootFolder.Files.Add(fileCreationInformation);
18: file.ListItemAllFields["Column 1"] = "Value 1";
19: file.ListItemAllFields["Column 2"] = "Value 2";
20: file.ListItemAllFields.Update();
21:
22: _sharePointContext.ExecuteQuery();
23: }
Summary
This simple example shows how easy it is to upload a file to a SharePoint document list and provide additional column information.