Download file via Ajax request
Imagine a plugin embeded in a web page that provides a Base64 image encoded. This image should be generated and stored in the server side and then perform an automatic download.
Back-end: Ruby on Rails. Front-end: Jquery.
Use two methods (actions) in your controllers layer. The first one receives the image (a string representing Base64 codification), decodes this string and writes it into filesystem:
The second action will be responsible for the download:
POST request to create the image. Then, using the ‘success’ callback, send a request to second action (with file name as a parameter in this case) in order to perform the download. Do this via
document.location.href (open a new browser window is also valid) and file will start downloading: