Force Download Through Js or Query

Force download through js or query

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.

Download File Using JavaScript/jQuery

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
href : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

Force download through js or query

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.

Download File after JQuery processing on a link

You can do this with a conditional statement. In my example I am using the confirm method, but you could also do this with a custom yes/no design.

What the code does is prompt the user to confirm that they want to download the file, if the user hits "ok" then the file will download, otherwise if they click "cancel" event.preventDefault(); is called which cancels the download.

$('a.download-video').click(function(event) {    if (!confirm('Download File?')) {      event.preventDefault();    }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a class="download-video" href="https://www.w3schools.com/html/mov_bbb.mp4?file=1&name=A Video" download> Download</a>

Force download GET request using axios

You're getting empty PDF 'cause no data is passed to the server. You can try passing data using data object like this

  axios    .post(`order-results/${id}/export-pdf`, {      data: {        firstName: 'Fred'      },      responseType: 'arraybuffer'    })    .then(response => {      console.log(response)
let blob = new Blob([response.data], { type: 'application/pdf' }), url = window.URL.createObjectURL(blob)
window.open(url) // Mostly the same, I was just experimenting with different approaches, tried link.click, iframe and other solutions })

starting file download with JavaScript

Try this lib https://github.com/PixelsCommander/Download-File-JS it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience.

Explained here - http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-type/

Seems to be ideal piece of code for starting downloading in JavaScript.

How can I download a file using window.fetch?

I temporarily solve this problem by using download.js and blob.

let download = require('./download.min');

...

function downloadFile(token, fileId) {
let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
return fetch(url, {
method: 'GET',
headers: {
'Authorization': token
}
}).then(function(resp) {
return resp.blob();
}).then(function(blob) {
download(blob);
});
}

It's working for small files, but maybe not working for large files. I think I should dig Stream more.

Download a file by jQuery.Ajax

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

fetch('https://jsonplaceholder.typicode.com/todos/1')  .then(resp => resp.blob())  .then(blob => {    const url = window.URL.createObjectURL(blob);    const a = document.createElement('a');    a.style.display = 'none';    a.href = url;    // the filename you want    a.download = 'todo-1.json';    document.body.appendChild(a);    a.click();    window.URL.revokeObjectURL(url);    alert('your file has downloaded!'); // or you know, something with better UX...  })  .catch(() => alert('oh no!'));


Related Topics



Leave a reply



Submit