2012-03-24 19 views
21

Necesito cargar un documento a una lista o carpeta de SharePoint utilizando el Modelo de objetos del lado del cliente de .NET (C#). ¿Cuál es la mejor manera de hacer esto?Subir un documento a una lista de SharePoint desde el lado del cliente Modelo de objetos

Los requisitos son los siguientes:

  • valores establecidos metadatos

  • No hay limitación en el tamaño del archivo de

  • debe trabajar con bibliotecas que exceden la vista de lista Umbral

+0

está preguntando por el modelo de JavaScript del lado cliente o el modo normal del cliente l? –

+0

^Dijo que está usando .NET (C#) CSOM. – BrainSlugs83

Respuesta

19

Para cargar documentos en Sharepoin t biblioteca de documentos de uso de función Después de modelo de objetos cliente:

public void UploadDocument(string siteURL, string documentListName, 
string documentListURL, string documentName, 

byte[] documentStream) 
{ 

using (ClientContext clientContext = new ClientContext(siteURL)) 
{   

//Get Document List 
List documentsList = clientContext.Web.Lists.GetByTitle(documentListName); 

var fileCreationInformation = new FileCreationInformation(); 
//Assign to content byte[] i.e. documentStream 

fileCreationInformation.Content = documentStream; 
//Allow owerwrite of document 

fileCreationInformation.Overwrite = true; 
//Upload URL 

fileCreationInformation.Url = siteURL + documentListURL + documentName; 
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
    fileCreationInformation); 

//Update the metadata for a field having name "DocType" 
uploadFile.ListItemAllFields["DocType"] = "Favourites"; 

uploadFile.ListItemAllFields.Update(); 
clientContext.ExecuteQuery(); 

} 
} 

siguiente enlace es también útil para usted 1) http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx

2) http://msdn.microsoft.com/en-us/library/ee956524.aspx

3) http://www.codeproject.com/Articles/103503/How-to-upload-download-a-document-in-SharePoint-20

+0

Gracias. Pregunta de seguimiento: el primer enlace explica cómo cambiar el límite de carga, pero es el código del lado del servidor. ¿Sabes cómo escribir e implementar un código del lado del servidor así? ¿Podemos escribir un script simple y ejecutarlo en el servidor? ¿Hay alguna otra manera de cambiar el límite (quizás el lado del cliente?)? –

+0

Desafortunadamente, este código no permite cargar archivos de 1.5 MB o más en SharePoint. Para eso, necesita usar el método SaveBindaryDirect, REST o FileCreationInformation.ContentStream. –

+0

Observé que cuando cargaba un archivo de esta manera con Versiones activadas obtengo dos versiones separadas en cada actualización: una al agregar un archivo y otra al llamar a ListItemAllFields.Update() – Kristopher

13

Otra forma es para usar el método SaveBinaryDirect. El método SaveBinaryDirect utiliza Web Based Authoring and Versioning (WebDAV) para cargar y descargar archivos. Sin construir su propio servicio WCF personalizado, WebDAV es la forma más eficiente de cargar y descargar archivos.

using (FileStream fs = new FileStream(FileToImport, FileMode.OpenOrCreate)) 
{ 
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, uri.LocalPath, fs, true); 
} 
Microsoft.SharePoint.Client.File newFile = web.GetFileByServerRelativeUrl(uri.LocalPath); 
context.Load(newFile); 
context.ExecuteQuery(); 

//check out to make sure not to create multiple versions 
newFile.CheckOut(); 

ListItem item = newFile.ListItemAllFields; 
item["Created"] = info.SourceFile.CreationTime; 
item["Modified"] = info.SourceFile.LastWriteTime; 
item.Update(); 

// use OverwriteCheckIn type to make sure not to create multiple versions 
newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn); 
+1

Al ingresar el archivo se actualizará el campo Modificado a la fecha/hora en que se registró el archivo, para que su ejemplo no funcione del todo como se esperaba. – Eccentropy

7

Sin embargo, otra opción para cargar un archivo en un sitio de SharePoint (incluyendo SharePoint Online) usando File.SaveBinaryDirect Method:

/// <summary> 
/// Uploads the specified file to a SharePoint site 
/// </summary> 
/// <param name="context">SharePoint Client Context</param> 
/// <param name="listTitle">List Title</param> 
/// <param name="fileName">File Name</param> 
private static void UploadFile(ClientContext context, string listTitle,string fileName) 
{ 
    using (var fs = new FileStream(fileName, FileMode.Open)) 
    { 
      var fi = new FileInfo(fileName); 
      var list = context.Web.Lists.GetByTitle(listTitle); 
      context.Load(list.RootFolder); 
      context.ExecuteQuery(); 
      var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name); 

      Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true); 
     } 
    } 
+1

Elegante ... gracias! – Colbs

6

me pareció que la parte del mensaje delax que actualiza nuevos atributos de archivo/columnas no lo hará trabajo, aquí es otra versión que incluso wroks para una biblioteca infopath personalizada con el campo promovido:

public string AddNewForm(string WebUrl, string NewTitle) 
    { 
     string strMsg = ""; 
     if (string.IsNullOrEmpty(WebUrl)) 
      return EmptyProcURL; 

     try 
     { 
      // Starting with ClientContext, the constructor requires a URL to the server running SharePoint. 
      using (ClientContext client = new ClientContext(WebUrl)) 
      { 
       //client.Credentials = System.Net.CredentialCache.DefaultCredentials; 

       // Assume that the web site has a library named "FormLibrary". 
       var formLib = client.Web.Lists.GetByTitle("FormLibrary"); 
       client.Load(formLib.RootFolder); 
       client.ExecuteQuery(); 

       // FormTemplate path, The path should be on the local machine/server ! 
       string fileName = @"D:\Projects\FormTemplate.xml"; 

       var fileUrl = ""; 

       //Craete FormTemplate and save in the library. 
       using (var fs = new FileStream(fileName, FileMode.Open)) 
       { 
        var fi = new FileInfo("newForm.xml"); 
        fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name); 
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true); 
       } 

       // Get library columns collection. 
       var libFields = formLib.Fields; 
       client.Load(libFields); 
       client.ExecuteQuery(); 

       Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl); 

       ListItem item = newFile.ListItemAllFields; 

       // Here the index of Title column is 9, you may use this format to update any column (even promoted fields). 
       // To find the index of interested column you should inspect libFields at debug mode, look in the libFields.Fields collection to find the index! 
       item[libFields[9].StaticName] = NewTitle ; 
       item.Update(); 
       client.ExecuteQuery(); 
      } 
     } 
     catch (Exception ex) 
     { 
      strMsg = ex.Message; 
     } 

     return strMsg; 
    } 
Cuestiones relacionadas