Serving files for download with AngularJS or JavaScript can be a handy feature to offer users the ability to access important files directly from your web application. In this article, we'll walk you through the process of serving a file for download using both AngularJS and plain JavaScript.
Using AngularJS
Angular allows you to create a Blob object from a file's content and serve it for download. Here's a step-by-step guide on how to achieve this:
1. Inject the `$window` service into your controller:
app.controller('MainController', ['$scope', '$window', function($scope, $window) {
// Controller code here
}]);
2. Create a function in your controller to handle file download:
$scope.downloadFile = function() {
var data = new Blob([fileContent], { type: 'text/plain' });
var url = $window.URL.createObjectURL(data);
$window.open(url);
};
3. When calling this function from your HTML template, make sure to pass the file content:
<button>Download File</button>
Using JavaScript
If you prefer using vanilla JavaScript, you can create a function to serve a file for download without any external libraries. Here's how you can do it:
1. Create a function in your JavaScript code:
function downloadFile(fileContent, fileName) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContent));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
2. Call this function with the file content and the desired file name:
var fileContent = 'Hello, world!';
var fileName = 'sample.txt';
downloadFile(fileContent, fileName);
By following these steps, you can easily serve files for download using either AngularJS or JavaScript in your web application. This functionality can enhance user experience and provide a convenient way for users to access important files directly from your site.