admin管理员组

文章数量:1323353

I hava a backbonejs view containing a button saying "download pdf". I also have the url available where the pdf can be found. I want that when user clicks on the button, the pdf file gets downloaded. Is it possible?

EDIT: My view code in backbone.js

savendownload: function () {
  this.$("#saveanddownload").button('loading');

  var that = this;
  var formData = this.fetchData();
  if (formData) window.invoices.create({
    buyer: formData.buyer,
    items: formData.items,
    pany: formDatapany,
    action: "savendownload"
  }, {
    wait: true,
    success: function (model) {
      var data = model.toJSON();

      var filename = data.filename;
      //download code here
    }
  });
}

I hava a backbonejs view containing a button saying "download pdf". I also have the url available where the pdf can be found. I want that when user clicks on the button, the pdf file gets downloaded. Is it possible?

EDIT: My view code in backbone.js

savendownload: function () {
  this.$("#saveanddownload").button('loading');

  var that = this;
  var formData = this.fetchData();
  if (formData) window.invoices.create({
    buyer: formData.buyer,
    items: formData.items,
    pany: formData.pany,
    action: "savendownload"
  }, {
    wait: true,
    success: function (model) {
      var data = model.toJSON();

      var filename = data.filename;
      //download code here
    }
  });
}
Share Improve this question edited Mar 2, 2013 at 10:40 jevakallio 36k4 gold badges108 silver badges114 bronze badges asked Mar 2, 2013 at 9:43 beNerdbeNerd 3,3746 gold badges59 silver badges95 bronze badges 1
  • Possible duplicate: stackoverflow./questions/3077242/… – Chris Commented Mar 2, 2013 at 9:45
Add a ment  | 

2 Answers 2

Reset to default 2

Don't use a button, use a link and set the href attribute to the URL of your PDF file. The browser will handle the file download for you, honoring the user's browser preferences.

<a href="your/file.pdf" />

If you need the link to look like a button, you can style it using CSS. See for example this SO thread.

Edit: AFAIK, you can't reliably initialize a file download from javascript. What you can do is to open a new window/tab with your pdf URL:

window.open("http://domain./document.pdf",'_blank');

But the user's browser can block the new window from being created. You might want to simply generate a download link:

$('<a>Click here to download PDF</a>').attr('href', filename).appendTo(that.$el);

And have the user click the link to initiate the file download.

use the "download" tag

<a href="assets/pdfs/yourdocument.pdf" download>Download PDF</a>

but does not wok at IE Explorer ;)

本文标签: javascriptforcing a pdf to download when clicked on buttonStack Overflow