Retrieve a document from a server and specifying the file name using AngularJS

Attempting to download a zip file from my server using a Spring MVC controller. Here is the AngularJS (1.5) controller code I am using to achieve this:

$http({
    url: '/myurl',
    method: 'GET',
    headers: {
        'Content-type': 'application/zip'
    },
    responseType: 'arraybuffer'
}).success(function (data,status,headers) {
    var blob = new Blob([data], {type: "application/zip"});
    var objectUrl = URL.createObjectURL(blob);                
    var file = headers('Content-Disposition');               

    window.open(objectUrl);

});

The above code works, but I need to specify the file name that I am receiving in the response header. When trying to use the file name obtained from header('Content-Disposition'), it currently gives a random file name.

I attempted the following code which works in Chrome but not in Mozilla. Is there a solution that can work across all browsers?


//var anchor = document.createElement("a");
//anchor.download = "ATMOSLogFiles.zip";
//anchor.href = objectUrl;
//anchor.click();

Appreciate any assistance provided! Thank you.

Answer №1

A solution leveraging blob technology:

To tackle this issue, you can explore the capabilities of angular-file-saver.

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 alternative method utilizing HTML5:

Another approach involves making use of the HTML5 download attribute / MDN documentation. This technique eliminates the need for blobs. The download attribute is compatible with all browsers that support AngularJS (excluding IE10/IE11 - IE Edge does offer compatibility).

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

Answer №2

Yes, @lin's response is accurate. I would like to further emphasize that in order to meet the requirements of the question, you can simply pass the file name set on the server to become the file name on the client side by following these steps:

To achieve this, first, you need to download and incorporate the angular-file-saver module into your application and include it as a dependency.


    var app = angular.module('myApp', ['ngFileSaver']);
    app.controller('mainCtrl', ['FileSaver', 'Blob', '$http', '$scope', function(FileSaver, Blob, $http, $scope) {
        // make an ajax call to the server
        $scope.download = function() {
            var req = {
                url: 'your server URL',
                method: 'GET',
                responseType: 'arraybuffer'
            };
            
            $http(req).then(function(resp){
                var serverData = new Blob([resp.data], {type: resp.headers()['content-type']});
                FileSaver.saveAs(serverData, resp.headers()['content-disposition']); // Passing the file name set on the server to the FileSaver function
            });
        }
    }]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A customizable JavaScript NPM Package designed to specifically escape XML special characters while preserving the integrity of the XML tags

Seeking recommendations for a JavaScript npm package that can escape the values in an XML document while preserving the XML tags. Ideally, looking for a solution that only allows letters A-Z (upper and lower case), digits 0-9, and spaces within the value ...

Sort your Laravel pagination table effortlessly with just one click

Here is my current setup: <table class="table table-striped"> <tr> <th> Item Image </th> <th> Item Number </th> <th> Item Name </th> <th> Description </th> ...

When hovering over certain transitioning elements in a D3JS chart, the animation execution is paused if other elements are also in the process of transitioning

Currently, I have been designing a horizontal bar chart and experimenting with transitions on various elements like rect and circle. The transitions are applied to attributes like width and r to achieve the desired effect. Everything seems to be working fi ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Discovering the number of intervals running at any given time within the console - JavaScript

I'm having trouble determining if a setInterval() is active or has been cleared. I set up an interval and store it in a variable: interval = setInterval('rotate()',3000); When a specific element is clicked, I stop the interval, wait 10 sec ...

Unable to populate data to HTML table using AJAX success function

When I use AJAX to filter data in the table, the data is not showing up. Instead, the data on the table disappears. Below is the script code I am using: $(document).ready(function() { $("#inputJenis").change(function() { var key = $(this).val ...

Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application. One of the functions in this library that I find particularly useful is: var defaultDecimalRounding=3 function formatNumber(number) { if (isNaN(number.value) == tr ...

The semantic-ui-react searchable dropdown feature may not show all of the options from the API right away

For some reason, when I attempt to call an API in order to populate the options for semantic UI, only a portion of the options are displayed initially. To view the full list, I have to first click outside the dropdown (blur it) and then click inside it aga ...

"Sorry, but window.print function is not available in this environment

Whenever I try to execute something in jest, I keep encountering the same error message: console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Not implemented: window.alert at module.expor ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

Refresh the Node.js page to generate fresh data upon reloading the page

I am currently running a web page on Node.js using the default folder setup provided by WebStorm, and I am utilizing ejs for rendering pages. To start the server, I run node bin/www with the following code snippet: ***preamble*** var app = require('. ...

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

Tips on removing v-bind directives from HTML code in VueJS

So, I've been working with Vue code and HTML recently. Take a look at this example: Vue.component('area-selectors-box', { template: ` <div class="area-selectors-box"> <area-selector v-for="(select, index) in selects" : ...

Interactive Vue.js canvases that adapt and respond to various

I am currently working on adjusting my canvas to fit within its container in a Vue component. When I call resizeCanvas() in the mounted hook, I notice that the container's height and width are both 0. How can I create a canvas that dynamically fits it ...

Enhancing Angular 2 functionality: Utilizing component input/output for service property updates

Currently learning Angular 2 and trying to grasp the concept of when to utilize a component's input/output versus updating a service property (potentially coupled with an EventEmitter for required updates). Imagine I have a collection of tasks, each ...

The header Origin:file:// from the Ionic native app is generating issues

While working on my simple Todo app in Ionic 1, I encountered an issue with the Origin header, specifically related to CORS. Running ionic serve works perfectly fine in the browser and allows me to make requests to my REST API on Apache (Tomcat). Howev ...

Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/ https://i.sstatic.net/r8Vxh.png I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created ...

What is the best method for developing a live text display switcher that works across different pages?

Hello everyone! I am currently in the process of creating a display toggler for my website. I have two separate pages, index.html and toggler.html. In index.html, the "TEXT" is displayed, while toggler.html contains the actual toggler or switch button. Whe ...

Turn on the text field when the enter key is pressed

I've searched online for solutions, but none of them have resolved my issue. Upon loading my page, I am able to successfully have my JS file select the first textfield. However, I am struggling with getting it to proceed to the next textfield when th ...