Wednesday, January 25, 2017

How to ensure the file upload succeed using CSOM in Sharepoint Add-ins development?

when we implement the file upload to sharepoint document library. we might not able to log the error from sharepoint, which will cause the the failure of file upload.

we can use the approach that return the document id after the file is uploaded to sharpeoint dcoment library. we can verify the document id to check the result of file upload. if the document id is return, it indicated that the document is successfully upload to sharpeoint. otherwise i will be failed.

here is the snipet of code to handle the above logic.

private string UploadFileToSharepoint(Byte[] fileData, string newFileName)
        {
         
            string guidId = string.Empty;
            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                using (var clientAppContext = spContext.CreateAppOnlyClientContextForSPHost())
                {
                    List list = clientAppContext.Web.Lists.GetByTitle(sListTitle);
                    FileCreationInformation newFile = new FileCreationInformation();
                    newFile.Overwrite = false;
                    using (newFile.ContentStream = new MemoryStream(fileData))
                    {
                        newFile.Url = newFileName;
                        Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile);
                        clientAppContext.Load(uploadFile, u => u.ListItemAllFields.Id);
                        clientAppContext.ExecuteQuery();
                        guidId = uploadFile.ListItemAllFields.Id.ToString();
                    }
                    return guidId;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

No comments:

Post a Comment