• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

329
Views
Force download through js or query

Is it possible to force a download through JS or Javascript i-e the web page should not open the file in new tab in the browser but to pop up to let the user to choose eith "save as" or open with ???

about 3 years ago · Santiago Trujillo
3 answers
Answer question

0

With the advent of HTML5 you could just use the new property download in the anchor tag.

The code will look something like

<a download="name_of_downloaded_file" href="path/to/the/download/file"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. Should I mention that I didn't check it in IE? :P

Edited the download attribute after comment from sstur


https://caniuse.com/#feat=download

about 3 years ago · Santiago Trujillo Report

0

dynamic create link and click it with download attribute for force download as file:

var anchor = document.createElement('a');
anchor.href = this.props.download_url;
anchor.target = '_blank';
anchor.download = this.props.file_name;
anchor.click();

Take a notice that i didn't even added it to DOM, so it's fast.

P.S download attribute won't work with IE. But it will just open link in new tab. http://caniuse.com/#feat=download

about 3 years ago · Santiago Trujillo Report

0

You can not force that behavior from JavaScript, the HTTP Headers need to be set on the server side:

Content-disposition=attachment; filename=some.file.name

The way you can solve the problem is to let your AJAX method redirect the user to the URL of the PDF:

location.replace('path/to.pdf');

(The above HTTP headers must be set for the PDF)


Update

At the time of this answer, it wasn't possible. Now it is, scroll down to see the other answer saying so.

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error