Combining distant documents using JavaScript

I have a question regarding merging files on a remote site. Let's say there are 2 files stored at the following locations:

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

Is it possible to merge these files before allowing the user to download them?

File 1: file1.txt

This is the content in file1.txt

File 2: file2.txt

But this is the content in file2.txt

Merged File: merged_file.txt (The file that will be presented to the user for download)

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

Follow-up Questions:

  • If the remote files have Content-Disposition: attachment as a header, is it still possible to merge them?
  • If merging is not feasible, can the files be combined into a single downloadable ZIP file instead of multiple text files?

Answer №1

To easily download the contents of multiple files, you can use a technique like this where each file is loaded into an array and action is taken once all the files have finished downloading. Additional logic will be needed to organize the files properly and ensure that all the downloads are complete.

function fetchFile(target, callback) {

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

fetchFile("file_a", onFetchComplete);
fetchFile("file_b", onFetchComplete);

document.loadedFiles = [];

function onFetchComplete(data) {

    document.loadedFiles.push(data);
}

You can then utilize a method similar to this to transfer the downloaded files from the JavaScript cache to the user's desktop.

function initiateDownload() {

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

    invisibleElement.href = 'data:attachment/text,' + encodeURI(document.loadedFiles);
    invisibleElement.target = '_blank';
    invisibleElement.download = 'downloaded-files.txt';
    invisibleElement.click();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do not include objects in the search results that lack necessary information

My ng-repeat code looks like this: <div layout="row" flex layout-wrap layout-margin layout-padding> <tile ng-repeat="camp in ctrl.camps | filter:{ctrl.search} track by $index"></tile> </div> The ctrl.camps object array is str ...

Creating multifunctional arrays in HTML tables

My goal is to create tables where each cell changes its class upon being clicked. As I set up the table, I want to track the history of clicked cells in an array. Currently, the history array is stored in the 'clicked' array: array=[1,4,6,9] ...

Generate Array of Consecutive Dates using JavaScript

My array contains the following values (for example): [ 1367848800000: true, 1367935200000: true, 1368021600000: true, 1368108000000: true, 1368194400000: true, 1368367200000: true, 1368540000000: true, 1 ...

Obtain the text content within a textarea using jQuery

There is a text area that includes both html and regular text, and I need to extract both from the text area. However, it seems that the current code is only retrieving the html code. HTML CODE <textarea id='post'> <div class="separato ...

Terser is causing ng build --prod to fail

When I run ng build --prod on my Angular 7 application (which includes a C# app on the BE), I encounter the following error: ERROR in scripts.db02b1660e4ae815041b.js from Terser Unexpected token: keyword (var) [scripts.db02b1660e4ae815041b.js:5,8] It see ...

Tips on storing the amount of time a user devotes to answering questions on my form into a database

I am facing an issue with storing the "duration" in my database. The "duration" I aim to store is the time spent by the user answering a question I created. When they click the submit button, I want to save the duration they spent in the database. Below i ...

Show personalized information in a title tooltip

I am working on a project that involves displaying user information from a list specific to each user when their name is hovered over. I have successfully created the list, but now I want to pull data from a database and show it as a tooltip or popup wit ...

The input of type 'string' cannot be assigned to type 'ChartType'

html code snippet <div style="width: 100%; display: block"> <canvas *ngIf="loaded" baseChart [data]="barChartData" [labels]="barChartLabels" [options]="bar ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Retrieve information using server-side rendering

I'm faced with a situation where my page utilizes query parameters to fetch data via SSR. The challenge arises when these query parameters frequently change, triggering a re-fetch of the data using SSR despite there being no client-side data fetching ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...

SuperAgent - Refresh the initial request with a new bearer token upon encountering unauthorized access

Issue: I encountered a problem while attempting to resend my original request using superagent. Here is some pseudo code that I came up with: function retryRequest({ params }) { return superagent.post(url) .set("Authorization", `Bear ...

Connect user input to a predefined value within an object

I am currently working on developing a timesheet application that allows users to input the number of hours they work daily. The user data is stored in an object, and I aim to display each user's hours (duration) in an input field within a table. An i ...

Strange response received from Stack Overflow API request

Having some issues with the code I'm using to call the Stack Overflow API: var request = require('request'); var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&sit ...

Browser Compatibility with AngularJS

Encountering an issue with AngularJS compatibility - are there any features not supported by Google Chrome? We have developed the AngularUI Calendar and utilized the JSFiddle link below: http://jsfiddle.net/joshkurz/xqjtw/52/ The UI calendar works on Fi ...

No data was submitted with the HTML form post request in the formData object

I am encountering an issue while trying to use the formdata object to send form data to my server. The formdata object appears blank when attempting to send the data, and it only prints out "{}". I have updated jQuery to version 11.1 which is supposed to s ...

What is the best way to display my 'React Loading Spinner' component at the center of my view?

Whenever I use the Loading as my parent component for the Layout component, it always shows up in the center of the page instead of within my view. How can I adjust its positioning? ...

Currently, I am utilizing a Google script to import my emails into a spreadsheet. I am seeking help in identifying and fixing a duplication issue that

For the past few weeks, I have been running a script to gather task data for my company. The script has been running smoothly since 09/03/2023, but recently it started duplicating entries and causing confusion in identifying which tasks are necessary and w ...

Creating an animated link with a dynamic underline featuring a trio of vibrant colors

I'm having trouble figuring out how to animate my links on hover with 3 different colors. I attempted using the linear-gradient property but it doesn't seem to be working. Any suggestions on how to proceed? Below is an example of what I'm a ...

The Bootstrap carousel refuses to slide when new dynamic data is introduced

I imported data from a database, but the items are displaying separately and do not change or slide as they should. I attempted to use JavaScript to fix this issue, but unfortunately, it did not work. When I tried using the carousel-item class, it only mad ...