Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading files with Ember app

Tags:

ember.js

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?

like image 533
Ruslan Avatar asked Nov 19 '14 15:11

Ruslan


3 Answers

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>

like image 104
Wojciech Wieroński Avatar answered Oct 17 '22 15:10

Wojciech Wieroński


  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>

like image 22
ToddSmithSalter Avatar answered Oct 17 '22 14:10

ToddSmithSalter


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'));
like image 22
Stéphane Bruckert Avatar answered Oct 17 '22 14:10

Stéphane Bruckert