Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading files in a SPA

How does one go about setting up file download in a Single Page Application, without triggering a reload?

I have had a situation where a PDF file is generated on the server and needs to be given to the client for download. Sending it as an application/octet-stream does nothing useful in a SPA, because files can't be sent over AJAX.

The best I came up with is saving the generated file in a temp folder on the server, sending file's URL to the client and doing window.open(url). The problem is that different browsers open files differently. Firefox for instance, by default, opens PDFs in the same tab, using their PDF.js, disrupting the whole SPA idea. But doing a window.open(url, '_blank') often triggers popup blockers etc. Other file types can cause God knows what...

Is there a cross-browser, safe, general method for downloading files in a SPA?

like image 726
Sljux Avatar asked Jan 24 '14 11:01

Sljux


People also ask

How do you download a file using react?

Use the download Attribute to Download Files in React Typically, web developers use the anchor element <a> to navigate another page. The <a> element also accepts the download attribute. It tells the browser to save the file located at the specified URL instead of changing the URL.

What is difference between SPA and web application?

There are two general approaches to building web applications today: traditional web applications that perform most of the application logic on the server, and single-page applications (SPAs) that perform most of the user interface logic in a web browser, communicating with the web server primarily using web APIs.

How does SPA application work?

A single-page application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current web page with new data from the web server, instead of the default method of a web browser loading entire new pages.

How does downloading a file from a website work?

When they download it, users make a copy of the data from what is on the central computer, called the server. In general use, the word download is used for both the process of copying the data and for the resulting file. Download is also mostly used in the context of copying data from a larger central server.


1 Answers

In SPA application I wrote a while back the the window.location.href = '...' did the trick and worked correctly for most browsers, but the contentType and content-disposition header of the page being downloaded is what makes the biggest difference. if the browser can recognize the file as a type do be downloaded then chances are the SPA won't break on redirect. Also just a quick note SPA frameworks like Angular sometimes allow for target='_new' and target='_self' on their a tags without interfering with the routes and such.

like image 66
Warrenn enslin Avatar answered Nov 02 '22 17:11

Warrenn enslin