Download multiple attachments from SharePoint list using ECMAScript Client Object Model

Hi,

I would like to download all the attachments of the list item using ECMAScript Client Object Model.

It would be nice if I get a download window to specify the path to save the documents.

Please assist me how to download all the attachments of the item in ECMAScript.

Regards,

Vidya Lokesh

July 29th, 2015 1:06pm

Hi Rupesh, 

Thanks for your response. 

The link which you have shared is getting URL of the attachment. But I want to download all the attachments using ECMAScript.

I am able to download the list Item attachments using .net Managed code Client object model but I need it in ECMAScript. 

Here is code to download attachment in Managed code. Let me know how to download it in ECMAScript.

void DownLoadattListAchment() { string SiteURL = @"SharePointSiteURL"; try { ClientContext context = new ClientContext(SiteURL); { Web web = context.Web; List list = web.Lists.GetByTitle("Test"); context.Load(list); context.ExecuteQuery(); Folder folder = web.GetFolderByServerRelativeUrl("Lists/test/Attachments/"+1); context.Load(folder); context.ExecuteQuery(); FileCollection attachments = folder.Files; context.Load(attachments); context.ExecuteQuery(); NetworkCredential credentials = new NetworkCredential("UserName", "Password", "domain"); WebClient client1 = new WebClient(); client1.Credentials = credentials; string downloadLocation = @"D:\MultipleDoc\"; foreach (Microsoft.SharePoint.Client.File oFile in folder.Files) { byte[] fileContents = client1.DownloadData("http://domain:8888" +oFile.ServerRelativeUrl); //FileStream fStream = new FileStream(downloadLocation + oFile.Name, FileMode.Create); FileStream fStream = new FileStream(downloadLocation + oFile.Name, FileMode.Create); fStream.Write(fileContents, 0, fileContents.Length); fStream.Close(); } } } catch (Exception ex) { } }


July 30th, 2015 1:15pm

Hi,

We can getting URL of the attachments using ECMAScript, then use jQuery code to download it.

Here is a jQuery plugin for your reference:

http://jquer.in/random-jquery-plugins-for-superior-websites/multidownload/

Best Regards

Free Windows Admin Tool Kit Click here and download it now
July 31st, 2015 9:12am

it is quite easy to rewrite first part of the code which gets list of all attachments from managed .Net client object model to javascript object model. The only thing which you should notice is that you will need to run your javascript code from the same site to where you will make requests (you can't use NetworkCredentials in javascript like in .Net example). After that you will need to download these attachments as single action. You may do it by opening multiple popup windows which will start own download: Download multiple files with a single action.
July 31st, 2015 10:02am

it is quite easy to rewrite first part of the code which gets list of all attachments from managed .Net client object model to javascript object model. The only thing which you should notice is that you will need to run your javascript code from the same site to where you will make requests (you can't use NetworkCredentials in javascript like in .Net example). After that you will need to download these attachments as single action. You may do it by opening multiple popup windows which will start own download: Download multiple files with a single action.
Free Windows Admin Tool Kit Click here and download it now
July 31st, 2015 10:02am

You can use below code, just make necessary modifications  to get list attachments. 

using Microsoft.SharePoint.Client;
using NLog;
using System;
using System.IO;
using System.Net;
 
namespace SiteActions.Task
{
  class Program
  {
  //You can get NLog from NuGet
  //http://www.nuget.org/packages/nlog
  private static Logger logger = LogManager.GetCurrentClassLogger();
 
  static void Main(string[] args)
  {
    try
    {
    int startListID;
    Console.WriteLine("Enter Starting List ID");
    if (!Int32.TryParse(Console.ReadLine(), out startListID))
    {
      Console.WriteLine("Invalid ID");
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
      return;
    }
 
    String siteUrl = "http://siteaction.net/sites/teamsite";
    String listName = "SharePoint List Name";
    NetworkCredential credentials =
                new NetworkCredential("username", "password", "domain");
 
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
       Console.WriteLine("Started Attachment Download " + siteUrl);
       logger.Info("Started Attachment Download" + siteUrl);
       clientContext.Credentials = credentials;
 
       //Get the Site Collection
       Site oSite = clientContext.Site;
       clientContext.Load(oSite);
       clientContext.ExecuteQuery();
 
       // Get the Web
       Web oWeb = clientContext.Web;
       clientContext.Load(oWeb);
       clientContext.ExecuteQuery();
 
       CamlQuery query = new CamlQuery();
       query.ViewXml = @"";
 
       List oList = clientContext.Web.Lists.GetByTitle(listName);
       clientContext.Load(oList);
       clientContext.ExecuteQuery();
 
       ListItemCollection items = oList.GetItems(query);
       clientContext.Load(items);
       clientContext.ExecuteQuery();
 
       foreach (ListItem listItem in items)
       {
          if (Int32.Parse(listItem["ID"].ToString()) >= startListID ){
 
          Console.WriteLine("Process Attachments for ID " +
                listItem["ID"].ToString());
 
          Folder folder =
                oWeb.GetFolderByServerRelativeUrl(oSite.Url +
                "/Lists/"+listName+/Attachments/" +
                listItem["ID"]);
 
          clientContext.Load(folder);
 
          try
          {
             clientContext.ExecuteQuery();
          }
          catch (ServerException ex)
          {
             logger.Info(ex.Message);
             Console.WriteLine(ex.Message);
             logger.Info("No Attachment for ID " + listItem["ID"].ToString());
             Console.WriteLine("No Attachment for ID " + listItem["ID"].ToString());
          }
 
          FileCollection attachments = folder.Files;
          clientContext.Load(attachments);
          clientContext.ExecuteQuery();
 
          foreach (Microsoft.SharePoint.Client.File oFile in folder.Files)
          {
             logger.Info("Found Attachment for ID " +
                   listItem["ID"].ToString());
 
             Console.WriteLine("Found Attachment for ID " +
                   listItem["ID"].ToString());
 
             FileInfo myFileinfo = new FileInfo(oFile.Name);
             WebClient client1 = new WebClient();
             client1.Credentials = credentials;
 
             logger.Info("Downloading " +
                   oFile.ServerRelativeUrl);
 
             Console.WriteLine("Downloading " +
                   oFile.ServerRelativeUrl);
 
             byte[] fileContents =
                   client1.DownloadData("http://siteaction.net" +
                   oFile.ServerRelativeUrl);
 
             FileStream fStream = new FileStream(@"C:Temp" +
                   oFile.Name, FileMode.Create);
 
             fStream.Write(fileContents, 0, fileContents.Length);
             fStream.Close();
          }
        }
      }
    }
    }
    catch (Exception e)
    {
      logger.ErrorException(e.Message, e);
      logger.Error(e.StackTrace);
      Console.WriteLine(e.Message);
      Console.WriteLine(e.StackTrace);
    }
    }
  }
}
Above uses client object model and can easily be run from console tool.
August 1st, 2015 7:44am

You can use below code, just make necessary modifications  to get list attachments. 

using Microsoft.SharePoint.Client;
using NLog;
using System;
using System.IO;
using System.Net;
 
namespace SiteActions.Task
{
  class Program
  {
  //You can get NLog from NuGet
  //http://www.nuget.org/packages/nlog
  private static Logger logger = LogManager.GetCurrentClassLogger();
 
  static void Main(string[] args)
  {
    try
    {
    int startListID;
    Console.WriteLine("Enter Starting List ID");
    if (!Int32.TryParse(Console.ReadLine(), out startListID))
    {
      Console.WriteLine("Invalid ID");
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
      return;
    }
 
    String siteUrl = "http://siteaction.net/sites/teamsite";
    String listName = "SharePoint List Name";
    NetworkCredential credentials =
                new NetworkCredential("username", "password", "domain");
 
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
       Console.WriteLine("Started Attachment Download " + siteUrl);
       logger.Info("Started Attachment Download" + siteUrl);
       clientContext.Credentials = credentials;
 
       //Get the Site Collection
       Site oSite = clientContext.Site;
       clientContext.Load(oSite);
       clientContext.ExecuteQuery();
 
       // Get the Web
       Web oWeb = clientContext.Web;
       clientContext.Load(oWeb);
       clientContext.ExecuteQuery();
 
       CamlQuery query = new CamlQuery();
       query.ViewXml = @"";
 
       List oList = clientContext.Web.Lists.GetByTitle(listName);
       clientContext.Load(oList);
       clientContext.ExecuteQuery();
 
       ListItemCollection items = oList.GetItems(query);
       clientContext.Load(items);
       clientContext.ExecuteQuery();
 
       foreach (ListItem listItem in items)
       {
          if (Int32.Parse(listItem["ID"].ToString()) >= startListID ){
 
          Console.WriteLine("Process Attachments for ID " +
                listItem["ID"].ToString());
 
          Folder folder =
                oWeb.GetFolderByServerRelativeUrl(oSite.Url +
                "/Lists/"+listName+/Attachments/" +
                listItem["ID"]);
 
          clientContext.Load(folder);
 
          try
          {
             clientContext.ExecuteQuery();
          }
          catch (ServerException ex)
          {
             logger.Info(ex.Message);
             Console.WriteLine(ex.Message);
             logger.Info("No Attachment for ID " + listItem["ID"].ToString());
             Console.WriteLine("No Attachment for ID " + listItem["ID"].ToString());
          }
 
          FileCollection attachments = folder.Files;
          clientContext.Load(attachments);
          clientContext.ExecuteQuery();
 
          foreach (Microsoft.SharePoint.Client.File oFile in folder.Files)
          {
             logger.Info("Found Attachment for ID " +
                   listItem["ID"].ToString());
 
             Console.WriteLine("Found Attachment for ID " +
                   listItem["ID"].ToString());
 
             FileInfo myFileinfo = new FileInfo(oFile.Name);
             WebClient client1 = new WebClient();
             client1.Credentials = credentials;
 
             logger.Info("Downloading " +
                   oFile.ServerRelativeUrl);
 
             Console.WriteLine("Downloading " +
                   oFile.ServerRelativeUrl);
 
             byte[] fileContents =
                   client1.DownloadData("http://siteaction.net" +
                   oFile.ServerRelativeUrl);
 
             FileStream fStream = new FileStream(@"C:Temp" +
                   oFile.Name, FileMode.Create);
 
             fStream.Write(fileContents, 0, fileContents.Length);
             fStream.Close();
          }
        }
      }
    }
    }
    catch (Exception e)
    {
      logger.ErrorException(e.Message, e);
      logger.Error(e.StackTrace);
      Console.WriteLine(e.Message);
      Console.WriteLine(e.StackTrace);
    }
    }
  }
}
Above uses client object model and can easily be run from console tool.
Free Windows Admin Tool Kit Click here and download it now
August 1st, 2015 7:44am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics