Ruslan
Ruslan

Reputation: 1301

Downloading files with Ember app

I have Ember App (built with Ember-CLI). On the backend I have Rails application which handles requests. Lets say that my API has following routes:

/model — returns list of models

/model/1 — returns model

/model/1/download — returns file

How can I force Ember app to start file download (using /download path) and how can I construct link for file download from within Ember app?

Upvotes: 5

Views: 6420

Answers (3)

Stéphane Bruckert
Stéphane Bruckert

Reputation: 22903

Don't do any of these manually, keep it simple and use ember-cli-file-saver!

// models/invoice.js
export default Model.extend({
  invoiceNumber: attr('number'),

  download: memberAction({ path: 'download', type: 'GET', ajaxOptions: { arraybuffer: true } })
});
// in a component
invoiceModel
  .download()
  .then((pdfContent) => this.saveFileAs('invoice.pdf', pdfContent, 'application/pdf'));

Upvotes: 1

ToddSmithSalter
ToddSmithSalter

Reputation: 715

  1. If you're going to hit the endpoint and return the file contents, I believe you'll need to set the Content Disposition header. More details here: Force download through js or query

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

  1. If you are linking to the file directly, you could use the HTML5 download attribute;

<a href="{{model.download}}" download>Download File</a>

Upvotes: 3

Wojciech Wieroński
Wojciech Wieroński

Reputation: 457

Why don't you just return the URL path for the download in your model for "/model/1". Then you can easily create links in your handlebars templates like so:

<a href="{{model.download}}" target="_blank">Download File</a>

Upvotes: 3

Related Questions