-1

How I can upload image to a SharePoint List "custom List" not library using CSOM C#?

Here is what I have tried so far:

FieldUrlValue url = new FieldUrlValue();
url.Url = FileUpload.PostedFile.FileName;  
url.Description = "Your description here"; 
newItem["Image"] = url;
IronAces
  • 1,857
  • 1
  • 27
  • 36
zzzz
  • 1
  • 4
  • I have error "the url is invalid" when upload image from desktop – zzzz Nov 11 '16 at 12:01
  • if you use a URL (field URL in your custom list) your image need to already be on the SharePoint (and set the URL from sharePoint not your local computer). That's why you have an Error "The URL is invalid" – Nico Nov 14 '16 at 13:12

2 Answers2

2

You can use this code to upload documents into SharePoint via the CSOM:

using (ClientContext ctx = new ClientContext("http://urlToYourSiteCollection")) {
    FileCreationInformation fci = new FileCreationInformation();
    fci.Content = System.IO.File.ReadAllBytes("PathToSourceDocument");
    fci.Url = System.IO.Path.GetFileName("PathToSourceDocument");
    Web web = ctx.Web;
    List targetDocLib = ctx.Web.Lists.GetByTitle("yourTargetLibrary");
    ctx.ExecuteQuery();
    Microsoft.SharePoint.Client.File newFile = targetDocLib.RootFolder.Files.Add(fci);
    ctx.Load(newFile);
    ctx.ExecuteQuery();
}

If you want to set properties of the new item, you can do it this way:

ListItem lItem = newFile.ListItemAllFields;
lItem.File.CheckOut(); //CHECK OUT VERY IMPORTANT TO CHANGE PROPS
ctx.ExecuteQuery();
lItem["yourProperty"] = "somewhat";
lItem.Update();
lItem.File.CheckIn("Z", CheckinType.OverwriteCheckIn);
ctx.ExecuteQuery();
dns_nx
  • 3,651
  • 4
  • 37
  • 66
  • Hi, I tried your code and it works perfect, i have a lookup field in image library, how can i set value to that, lItem["my lookup field"] = value; does not work. – sairfan Mar 28 '18 at 17:39
  • This solution should even work with Lookup fields. But I will try to check. – dns_nx Mar 29 '18 at 07:09
  • thanks it works, `FieldLookupValue lookupf = new FieldLookupValue(); lookupf.LookupId = 1; lItem["Account"] = lookupf;` – sairfan Mar 29 '18 at 18:07
-1

If you need to upload files to a SharePoint site please visit the following link where it is explained how to read and upload files using CSOM

How to download/upload files from/to SharePoint 2013 using CSOM?