File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint:

<iron-ajax
  id="ajax"
  method="POST"
  url="/export/"
  params=''
  handle-as="json"
  on-response="handleResponse"
</iron-ajax>

The response from my Koa/Express-server includes a read stream as shown below:

router.post('/export', function*(){

  var file = __dirname + '/test.zip';
  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  this.set('Content-disposition', 'attachment; filename=' + filename);
  this.set('Content-type', mimetype);
  this.body = fs.createReadStream(file);
})

In the function handleResponse(), how can I trigger the download without directly handling the response? Preferably, I would like to initiate the download without any intermediary steps.

The expected response headers are as follows:

Content-disposition: attachment; filename=test.zip
Connection: keep-alive
Transfer-Encoding: chunked
Content-type: application/zip

Answer №1

If you provided your file data in octet stream format, you could trigger the download as demonstrated here: How to save a file using Javascript with a specific name

uriContent = "data:application/octet-stream," + encodeURIComponent(dataFromServer);

newWindow=window.open(uriContent, 'customfilename.txt');

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

What is the best way to create fading text effects in an AngularJS application?

Running an AngularJS web application that showcases three words for 5 seconds each: Hello, World & Goodbye. The controller setup is as follows: self.currentIndex = 0; self.myTexts = ['Hello', 'World', 'Goodbye']; self.cu ...

What is the best way to maintain data types of variables within an object sent via ajax?

I'm sending an object via ajax to a PHP script for processing. Here's how I'm doing it: var Obj = {id:1, name:"John", value:12.1}; $.ajax({ url : "myfile.php", type : 'POST', data : Obj, success : ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...

Create a connection between a div and a React component, allowing for the seamless transfer of

I'm looking to implement a feature where clicking on a specific div will redirect the user to another page, similar to React Router. However, I currently lack the knowledge to make it happen. Below is the code snippet in question: const Card: React.FC ...

Exploring secure routes in Node.js with test cases using Mocha and Chai?

The function verifies whether the route is accessible or not function checkSessionCookieValidity(req, res, next) { if (!isValid(req.session)) { return res.status(401).json({ isLoggedIn: false }); } return next ...

Node.js: retrieving a webpage and waiting for it to load before extracting data

Is it possible to scrape a webpage using just node.js without relying on other libraries like phantom.js? That is the question I have been pondering lately. In my code below, I am requesting a webpage with request and then using cheerio to extract data by ...

Can you guide me on implementing AJAX to create and edit new posts while using the same HTML template in Python and Django?

I am in the process of transitioning to utilizing AJAX for form saving instead of solely relying on Python/Django (I am a complete beginner, so please excuse any mistakes). I have outlined what I aim to accomplish: https://i.stack.imgur.com/q3rfW.png url ...

Is there a JavaScript equivalent to the explode function in PHP with similar functionality

I'm facing an issue while attempting to split my string in JavaScript, here is the code I am using: var str = 'hello.json'; str.slice(0,4); //output hello str.slice(6,9); //output json The problem arises when trying to slice the second str ...

Having trouble getting the form to serialize properly, unable to locate the error. Frustrating!

Hello, Here is the jQuery code I am currently using: $('body').on('change','form#item-form', function(e){ e.preventDefault(); var data = $(this).serialize(); console.log( data ); }); and a form (inserted via que ...

Issue with ng-repeat rendering on screen

Creating a breadcrumb has been my latest project, so I decided to develop a service specifically for this purpose. In order to display all the breadcrumbs, I utilized an ng-repeat in my HTML. Additionally, I set up an event listener for '$routeChange ...

Generating socket.io functionality with the Express framework

After attempting the solution provided at Using socket.io in Express 4 and express-generator's /bin/www, I encountered an error message in the terminal on line 12 of /routes/messages.js: io.on('connection', function(socket){ TypeError: Canno ...

Issues with Ajax causing problems with updating information in <h:selectOneMenu>

How can I update a selectOneMenu based on the selection of another selectOneMenu? I need the user menu to be dynamically updated when a group is selected. Although I can see that the data for the user menu is being updated, it's not rendering as exp ...

The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER ...

Identify the Google Maps Marker currently displayed on the screen

Is there a way to generate a list of markers within the zoom range for Google Maps, similar to the functionality on this site I'm curious if I can achieve this using jQuery or if there is a built-in function for Google Maps v3? Thank you! ...

Rails 3.2 - form mistakenly submitted repeatedly

I am working on a project involving the Box model, which includes many box_videos. I have created an edit form to allow users to add box_videos to the box after it has been created: <%= form_tag "/box_videos", { method: :post, id: "new_box_videos", rem ...

"Utilizing jQuery to Send POST Requests on Rails - Dealing

Currently, I am running a JavaScript game from file:// and attempting to send a post request to a localhost Rails server in order to add a new high score. In my JavaScript: highScoresEntryView.keyHandlers = function() { var that = this; this.pa ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...

Is it feasible to utilize the return value of an Async call to display or conceal an alert message?

Before this gets closed as a duplicate, I have searched through numerous threads on the forum that do not address my specific question. Please take the time to read. Here is the scenario: when a user clicks a button, JavaScript needs to validate whether t ...