title: Copy multiple attachments from list to document library by javascript
body: <p>I have a list which each row has at most 1 attachment, and I am trying to copy each attachment from this list to a newly created picture library.</p>
  
  <p>I am able to copy 1 attachment by the following code,</p>
  
  <pre><code>var Files;
  var myContext;
  function CopyAtt(ItemID) {
  try {
          myContext = new SP.ClientContext.get_current();
          var myWeb = myContext.get_site().get_rootWeb(); 
  
          var folderPath = 'Lists/test/Attachments/' + ItemID;
          var Folder = myWeb.getFolderByServerRelativeUrl(folderPath);
  
          Files = Folder.get_files();
          myContext.load(Files);
  
          myContext.executeQueryAsync(Function.createDelegate(
                                      this, ExecuteCopyOnSuccess),
                                      Function.createDelegate(
                                      this, GetLeadsFail));                       
       }
      catch (err) {
          alert(err.Line);
      }
  }
  
  function GetLeadsFail(sender, args) {
      // Show error message
      alert('GetLeadsFail() failed:' + args.get_message());
  }
  
  function ExecuteCopyOnSuccess(sender, args) {
      for (var p = 0; p &lt; this.Files.get_count(); p++) {
          var file = Files.itemAt(p);
          var filename = file.get_name();     
      }       
      if (filename != null) {
              var newUrl = 'PictureLibrary/' + filename;
              file.copyTo(newUrl, true);
              myContext.executeQueryAsync(null, null);
      }
  }
  $(document).ready(function() {
       CopyAtt(3);
  }
  </code></pre>
  
  <p>When I try to call <code>CopyAtt(ItemID)</code> multiples times from <code>$(document).ready</code>, 
  the code is showing errors in console.</p>
  
  <pre><code>Uncaught TypeError: Cannot read property 'collectionHasNotBeenInitialized' of undefined
  Uncaught RangeError: Maximum call stack size exceeded
  </code></pre>
  
  <p>I suspect that it is related to Files but I cannot find any clues, can anyone give me some advice?</p>