How to Serve a File for Download with Angularjs or JavaScript

How do you serve a file for download with AngularJS or Javascript?

You can do something like this using Blob.

<a download="content.txt" ng-href="{{ url }}">download</a>

in your controller:

var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );

in order to enable the URL:

app = angular.module(...);
app.config(['$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}]);

Please note that

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

Source: MDN

Download a file from server and giving filename in angularjs

An blob based solution:

You could use angular-file-saver to achieve this.

var app = angular.module('myApp', ['ngFileSaver'])

app.controller('ExampleCtrl', ['FileSaver', 'Blob', function () {
$scope.download = function () {
var myData = new Blob([text], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(myData, 'text.txt');
}
}]);


An other solution based on HTML5:

A simple way by using the HTML5 download attribute / MDN documentation. No need for blobs. This attribute is supported by any browser & browser version which supports AngularJS (excluding IE10/IE11 - IE Edge does support it).

<a href="<downloadLink>" download="fileName">Download</a>

Download a file with AngularJS

First of all, your can't "hide/not public" a link in a web based technology (HTML/CSS/JavaScript) application. Downloads are handled by the client, so the Download/Link-URL must be public. You can try to "hide" protective params like e.g. IDs in the download URL by using a backend executed programming language like "PHP or node.js, etc.". In that way you can create hash URLs like http://www.myside.com/download/359FTBW!S3T387IHS to hide parameters like the recordId in your URL.

By knowing this, your solution is pretty easy. Just use the HTML attribute download like <a href="http://mydownloadurl" download>link text</a> to force the browser to download the href source. No ng-click is needed here. Unfortunately the download attribute is not supported by Safari browser. This doesn't realy matter while the browser is handling the download itself. Depending on the users system OS configuration the file will be downloaded or directly opened in a programm installed on that system. For example, a PDF file will be opened in a PDF Viewer if some pdf viewer application is available.

I wrote a Plunker which handles ng-href in a AngularJS controller $scope. I hope this is what you need.

Your controller:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.fileHref = 'http://www.analysis.im/uploads/seminar/pdf-sample.pdf';
});

Your view:

<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.14/angular.js" data-semver="1.3.14"></script>
<script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
<a ng-href="fileHref" download="yourFilename">Download</a>
</body>
</html>

How to download a zip file in AngularJS / FilesaverJS

You should have 2 separate rest services on backend for this so instead of serving all files at the same time and holding them in browser, you should retrieve list of available files from one rest endpoint and then on user's click retrieve specific file from another rest endpoint. Your service for file could look something like this:

function downloadFile(src) {
let header, startIndex, filename;
$http({
method: 'GET',
url: src,
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml,application/pdf;q=0.9,image/webp,*/*;q=0.8',
'Upgrade-Insecure-Requests': 1
},
responseType: 'blob'
}).then(function (successResponse) {
header = unescape(successResponse.headers()['content-disposition']);
startIndex = header.indexOf('filename=');
filename = header.slice(startIndex + 10,-1);
try{
saveAs(successResponse.data, filename);
}
catch(error){
// FileSaver error
}
}, function (errorResponse) {
// Server error has occurred during file downloading.
}

Where you need to specify response type to be blob. Variable src in this example would be specific endpoind serving desired file (here it's served from controller based on data retrieved from list of files available but you can build it here if you want based on file's id or something). In this case backend is serving full file name in exposed header so you can extract it and save file with it's proper name and format. Extraction in this example was for specific rest response but you should be able to change it to suite your needs.

Example: content disposition header would be string, something like:

Content-Disposition: attachment; filename="picture.png"

In this case service would extract that name and Filesaver would save file "picture.png".

How to download a text file based on a generated String using AngularJS?

In order to achieve this you have to create an a tag in your HTML:

<a download="content.txt" ng-href="{{ url }}">download</a>

Controller:

var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );

And to enable the URL:

app = angular.module(...);
app.config(['$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}]);

Source:
How do you serve a file for download with AngularJS or Javascript?

How to change file name when download it from server in AngularJS

Create a a html attribute and use that to download your file.

var file_path = 'row.entity.downloadUrl';
var a = document.createElement('A');
a.href = file_path;
a.download = 'you new file name';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

AngularJs trigger a file download by calling a REST endpoint

You can append an <a> tag, set file url to href property and trigger click to download file. check below code,

function DeliveriesController(deliveriesService){
var vm = this;
vm.deliveries = {};
vm.downloadXML = downloadXML;

function downloadXML(releaseSlug){
var url = APP_CONFIG.apiUrl + '/deliveries/' + releaseSlug + '/xml';
var expectedMediaType = 'xml';
var headers = {'User-Id':'abc','User-Name':'ABC XYZ', 'Workspace':'abc', 'Content-Type': 'application/xml', 'Accept': expectedMediaType};

$http.get(url,{
headers: headers
}).then(function (response){
console.log(response);
//=== add <a> tag and trigger click ===
var link = document.createElement('a');
link.addEventListener('click', function(ev) {
link.href = response.url; // url of the file to be downloaded
link.download = "name";
document.body.removeChild(link);
}, false);
document.body.appendChild(link);
link.click();
});
}


Related Topics



Leave a reply



Submit