0

I am trying to get the Files Urls from selected documents. I am using SPContext to make a call and then using a callback function to push results into an array then later in the code I loop through the array to access the urls so I can download the documents. However, the problem is that it downloads documents double times or triple times, depending on how many I have selected.

My questions are:

  1. how can I retrieve the urls of the selected documents. Is there a better way than the one I have so far?
  2. How can I download only a single copy of the document, thus avoiding double download of the same document?
  3. For my understanding, how can I call executeQueryAsync multiple times and store the response in an array as I have done below? Please let me know how can I improve my code.

I am using Sharepoint 2013. Thank you for your help.


function DownloadFiles(onComplete) {
        var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
        var count = selectedItems.length;
        if (count == 0) {
            alert("Please select an item from the list");
            return false;
        }
        var arrOfLinks = [];
        for (i in selectedItems) {
            var clientContext = new SP.ClientContext();
            var targetList = clientContext.get_web().get_lists().getByTitle(ctx.ListTitle);
            targetListItem = targetList.getItemById(selectedItems[i].id, 'FileLeafRef', 'ContentType', 'File', 'FileRef');

    
            clientContext.load(targetListItem);
            arrOfLinks.push(targetListItem);
            clientContext.executeQueryAsync(() => {
                onComplete(arrOfLinks);
            }, Function.createDelegate(this, this.onQueryFailed));
        }
    }
    
    function myCall() {
        DownloadFiles((arrayOfLinks) => {
          for (var i = 0; i < arrayOfLinks.length; i++) {
             var url = window.location.origin + arrayOfLinks[i].get_item('FileRef');
            window.location.href = `/_layouts/15/download.aspx?SourceUrl=${url}`;
           }
        });
    }
    
    function onQueryFailed(sender, args) {
        alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
    }

1 Answer 1

0

Have a look at this other post. I think it will answer your question:

Using getSelectedItems to get a field value instead of ID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.