Downloading the file from the specified URL is taking too much time when using the save as blob function

I have developed a service to retrieve and save files from a specified URL.

(function() {
    angular.module('SOME_APP')
        .service("downloadService", downloadService);

        function downloadService($http){

            var downloadFileFromUrl = downloadFileFromUrl;

            function downloadFileFromUrl(url){

                if(!url.length){
                    //TODO handle the error
                }

                else{
                    //extract the file name and extension for saving purposes:
                    var fileName;
                    for(var i=url.length; i>=0; i--){
                        if(url[i]=='/'){
                            fileName=url.slice(i+1, url.length);
                            console.log(fileName);
                            break;
                        }
                    }
                    $http({
                        url: url,
                        method: "GET",
                        responseType: 'arraybuffer'
                        }).success(function (data) {
                            var blob = new Blob([data], {type: '*/*'});
                            saveAs(blob, fileName);
                        }).error(function (data) {
                            console.log(data);
                            //TODO error handling
                    });
                }
            }

            return {
                    downloadFileFromUrl : downloadFileFromUrl
            }
        }
}());

After calling the service, it currently downloads the file first and then displays it in the browser with progress reaching 100%. How can I modify it to work normally by initiating the download in the browser and showing the progress gradually?

Answer №1

For my task, I needed to retrieve a file from a specified URL. I achieved this by utilizing the HTML5 anchor tag with the download attribute as shown below:

Within index.html:

<a id='linkToDownload' href="" download hidden></a>

And in my service file:

document.getElementById("linkToDownload").href = url;
document.getElementById("linkToDownload").click();

This method effectively resolved the issue at hand.

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

Event for terminating a Cordova application

We are looking for a way to send a notification to the user's device when our app is closed rather than just paused. On iOS, this occurs when you double click the home button and swipe up on the app, while on Android it happens when you press the Men ...

Enhance your Wordpress posts with a custom pop-up form for each individual button

On a page, there are various custom posts being displayed with the post type 'property', each containing a button: <button class="btn btn-primary">Submit Offer</button> This button is looped and shown below every post. What ...

The submitHandler() function in the jQuery validate method is experiencing delays when executing and processing the form submission

Currently, I am using the jQuery validate method to validate my form. I have implemented some code in the submitHandler() method, but it seems to be taking longer than expected to execute. Can anyone provide me with a solution to resolve this issue? $(&ap ...

Troubleshooting: jQuery AJAX failing to receive JSON data in HTTP request

Experimenting with HTML and jQuery to practice JSON requests, I conducted some research and attempted a small test. However, upon running the script in Google Chrome, only my HTML/CSS elements appeared instead of expected results. Below is the code snippet ...

Having trouble initiating the webdriver-manager on my Mac in order to run tests on Angular applications using Protractor

Recently, I have delved into the world of protractor. While attempting to kickstart the Selenium Server using webdriver-manager in protractor, an error has sprung up like a pesky bug: [19:32:29] I/start - java Dwebdriver.chrome.driver=/usr/local/lib/node ...

NextJS struggles to load EditorJS plugins

I am currently working on integrating EditorJS into my NextJS project. The editor is loading properly without any plugins, with only paragraph as a block option. However, I'm facing an issue when trying to add plugins using the tools prop which result ...

Error: The validation process failed due to missing information. The file name and path are both required for validation

In my current project, I am attempting to upload a file from the frontend to the backend and save it. However, I am encountering an error that looks like this: Error The error message is as follows: this.$__.validationError = new ValidationError(th ...

The Access-Control-Allow-Origin policy does not permit requests from applications running with an origin of null, specifically for those using a file:// URL

I am in the process of creating a webpage that utilizes jQuery's AJAX feature to fetch images from both Flickr and Panoramio. While the image retrieval from Flickr is functioning properly, I encounter an issue when attempting to use $.get(url, callba ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Determine the byte size of the ImageData Object

Snippet: // Generate a blank canvas let canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; document.body.appendChild(canvas); // Access the drawing context let ctx = canvas.getContext('2d'); // Extrac ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Warning message appears if date input field is left empty upon submission

After implementing angular-ui/ui-date for the date input and angular-auto-validate for form validation, I encountered an issue where the date input field shows a required message before submission. It seems that the problem may be caused by the built-in va ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

JavaScript's toFixed method for decimals

I am encountering an issue with displaying prices for my products. I have labels in the form of "span" elements with prices such as 0.9, 1.23, and 9.0. I am using the method "toFixed(2)" to round these prices to two decimal places. However, I have notice ...

Issue with directive in AngularJS: When trying to access scope.data, it appears

Initially, I came across the API address in this discussion: Laravel 4 and Angular JS and Twitter Bootstrap 3 Pagination Now, I am delving into this topic, and my script snippet goes like this: var app = angular.module('category', [ &ap ...

What is the best way to present a unique page overlay specifically for iPhone users?

When browsing WebMD on a computer, you'll see one page. However, if you access it from an iPhone, not only will you be directed to their mobile page (which is easy enough), but they also display a special overlay with a "click to close" button prompti ...

Utilize jQuery to trigger video playback based on the horizontal movement of the mouse

Utilizing this jQuery script to navigate back and forth in a video as the cursor moves along the x-axis. var mouseX; $(document).mousemove( function moveFunc(e) { mouseX = e.clientX; var timV = $("#deko_vid").get(0).duration; var valV = (timV*mouseX/$(do ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

Retrieve information from Node.js using Express

I am working on a server with Node.js and using Express to create a web application. I have successfully implemented a function called rss_interrogDB that retrieves an array from a database. Now, I am trying to use this array to display a list on the HTML ...