Service for downloading browser-generated data to disk.
This service provides methods for downloading content generated in JavaScript (text, images, etc.) as files.
It relies on the <a download>
functionality supported in current browsers and does not require any server
handling or flash plugins.
Installation can be done through bower:
bower install angular-download
In your page add:
<script src="bower_components/angular-download/angular-download.js"></script>
You can also use npm to install it:
npm install angular-download --save
This service is part of the download
module:
var app = angular.module('myApp', [..., 'download']);
Inject the download
service:
function MyController($scope, download, ...) {
$scope.downloadFile = function() {
download.fromData("contents of the file", "text/plain", "file.txt");
}
}
Downloads a file containing string data
as type mimeType
named fileName
.
function MyController($scope, download) {
$scope.downloadAsJson = function(someData) {
download.fromData(JSON.stringify(someData), "application/json", "download.json");
}
}
Downloads a file containing Base64-encoded string dataBase64
as type mimeType
named fileName
.
function MyController($scope, download) {
$scope.downloadAsJson = function(someData) {
download.dataBase64(JSON.stringify(btoa(someData)), "application/json", "download.json");
}
}
Downloads a file with contents defined by the dataUrl
named fileName
. This is useful for downloading binary
data, such as client-generated images.
function MyController($scope, download) {
$scope.downloadImage = function(img) {
download.fromDataURL(getImageDataURL(img), "download.png");
}
}
// Create a dataURL from an img element
function getImageDataURL(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
// Copy the image contents to the canvas
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/png");
}
Downloads a Blob
with contents defined by the dataBlob
named fileName
. This is useful for downloading binary
data, such as client-generated images.
function MyController($scope, download) {
$scope.downloadImage = function(img) {
getImageDataBlob(function(blob) {
download.fromBlob(blob, "download.png");
});
}
}
// Create a PNG Blob from an img element
function downloadImage(img, cb) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
// Copy the image contents to the canvas
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
if (canvas.msToBlob) {
// On IE, the msToBlob method returns the Blob value
cb(canvas.msToBlob);
} else {
// On standard browsers, the toBlob method calls the callback
canvas.toBlob(cb);
}
}
Copyright 2015 Stepan Riha. All Rights Reserved.
This may be redistributed under the MIT licence. For the full license terms, see the LICENSE file which should be alongside this readme.