1

I have a question. Suppose that I have 2 files on remote site.

  • http://example.com/path/to/file1.txt
  • http://example.com/path/to/file2.txt

Is it possible to be merged before letting the user download it?

file1.txt

This is the content in file1.txt

file2.txt

But this is the content in file2.txt

merged_file.txt (The file that the user will get)

This is the content in file1.txt
But this is the content in file2.txt

Follow up questions

  • If possible: can it be merged if the remote files have Content-Disposition: attachment as a header?
  • If impossible: can it be zipped together and let the user download a single file instead of multiple text files?
7
  • 1
    Use JavaScript / AJAX to asynchronously download both the files, assemble them, then do something like this to allow the user to download it. Commented Mar 25, 2020 at 14:51
  • Yes, these are all possible. Commented Mar 25, 2020 at 14:51
  • @HereticMonkey Merging is of course possible. But how do you zip them in browser? Commented Mar 25, 2020 at 14:52
  • 2
    @bravemaster How to Zip files using JavaScript? Commented Mar 25, 2020 at 14:54
  • @MattClark Thanks. I have a question (for clarity) at download both the files: does this means you have to save the files on the sever first? Commented Mar 25, 2020 at 14:59

1 Answer 1

2

Use something like this to download the contents of each file, load them into an array, then act on the array when all the files are done downloading. It wil require s ome more logic to assemble the files and to make sure all the files are actually done downloading, but it is possible.

function dl(target, callback) {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            callback(xhr.responseText);
        }
    }
    xhr.open("GET", target, true);
    xhr.send();
}

dl("file_a", onDone);
dl("file_b", onDone);

document.files = new Array();
function onDone(data) {

    document.files.push(data);
}

Then use something like this to download the files from the JS cache to the users desktop.

function download() {

    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/text,' + encodeURI(document.files);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'in-line.txt';
    hiddenElement.click();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.