AviatorX
AviatorX

Reputation: 532

I am trying to create a Download Button but file is not downloading?

I am creating download button having click listener which request server to download file

code click listener:

 downloadFileClick(event){
   $.ajax('/download', {data:{}}).done(function(data){

   }.bind(this));
 }

at server side following code is running

app.get('/download', function(req, res){
  var file = __dirname + '/write/imageout.png';
  res.download(file);
});

file is not downloading in browser. I checked response send from server to client it sending file content but it not downloading from browser.

Upvotes: 1

Views: 177

Answers (1)

Frank Roth
Frank Roth

Reputation: 6339

You can not download a file by making an ajax request to that file. The Browser will ignore this. You have to open the file via <a href="/download" download> or you can trigger that from jQuery:

var a = $("<a>");
a.attr("href", "/download");
a.attr("download", "img.png");  // this is important
a.appendTo("body");
a[0].click();
a.remove();

This should download the browser image correctly.

Upvotes: 2

Related Questions