Downloading Files through AngularJS on the Front End

When I click the download button next to the file name, I am retrieving the file content from the backend. The content is in bytes and the file can be of any type. How do I convert the data received from the backend into a file and automatically download it when receiving the response (file content)? I am new to HTML and AngularJS. Any suggestions or pointers would be greatly appreciated :)

Answer №1

Your backend needs to communicate the file's location to the front-end so that a link to the file can be created. It's recommended for the backend to generate a unique hash name for each file. The file can be retrieved through a Rest GET request as long as the backend webserver has the appropriate mime types set up.

To retrieve the file path, you would make a call to a service in your controller:

SomeController.$inject = ['$http'];
var SomeController = function($http) {

    var self = this;
    $http.get('/download-file-path').then(function(path) {
        self.path = path; 
    }

}

Then, in your view:

<div ng-controller='SomeController as vm'>
    <a ng-href="{{vm.path}}">Download</a>
</div>

When Angular calls GET: /download-file-path, the backend should return the file's name and path, such as /download/file-7dje79ae.xml. Angular will then populate the path in the a link. Upon clicking the download button, the user's browser will request /download/file-7dje79ae.xml and begin downloading the file.

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

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

Is there a way to make Phpstorm identify and acknowledge the usage of NextJS pages?

Just finished setting up my brand new NextJS app: function MyApp({ Component, pageProps }: AppProps) { return ( <Layout> <Component {...pageProps} /> </Layout> ) } export default MyApp However, PHPStorm keeps giving me ...

Unable to change from a String to a Timestamp due to incorrect formatting

Encountering an issue when attempting to send a date object from AngularJS to a Java Spring backend: Received the following error: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.sql.Timestamp] for value '2018 ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Guide on duplicating text and line breaks in JavaScript

There is some text that looks like this text = 'line 1' + "\r\n"; text+= 'line 2' + "\r\n"; text+= 'line 3' + "\r\n"; I have developed a function to help facilitate copying it to the clipboard ...

Tips on incorporating toggle css classes on an element with a click event?

When working with Angular typescript instead of $scope, I am having trouble finding examples that don't involve $scope or JQuery. My goal is to create a clickable ellipsis that, when clicked, removes the overflow and text-overflow properties of a spec ...

Utilize an array with dynamic referencing

I am attempting to reference a single index out of 30 different indices based on the user's actions, and then utilize ng-repeat to iterate through each item in the index. Controller: $scope.meals = [ { title: 'Abs', url:"#/app/mworkout ...

Unable to retrieve the string contained within an element - JavaScript object literal

I am currently facing an issue where I am attempting to retrieve the text content of two div elements with classes .class-date and .class-time, but I keep encountering an Uncaught TypeError stating "e.siblings is not a function". I believe this may be a ...

Remove the background color from a semi-transparent circular CSS div when it is being dragged

My circular div is being dragged for a drag and drop operation, but there's always a translucent square around it. How can I remove this unwanted effect? body{ background : #BBD1DF; } .dragdemo { width: 170px; height: 170px; line-hei ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Getting to the values within a JSON object that contains multiple arrays

Is there a way to retrieve array data from the json object data? const [data, setData] = useState([]) const getData = () => { axiosInstance .get(url + slug) .then(result => setData(result.data)) } useEffect(() = ...

What is the best way to merge multiple statements into one before passing them into a JavaScript method?

I am faced with several javascript statements like the ones listed below: $('#' + xxx_slot_name1).children().remove(); $('#' + xxx_ad_slot_name2).children().remove(); $('#' + xxx_ad_slot_name3).children().remove(); $('#& ...

Error: ytcfg and __ytRIL are undefined and cannot be referenced

For several months, I had smooth sailing with the YouTube IFrame Player API until recently when an unexpected exception popped up upon loading the player: Uncaught ReferenceError: ytcfg is not defined Upon inspecting the iframe, I noticed that yt.setConfig ...

Serializing ajax calls using `WHEN` and `DONE` in jQuery

I have several ajax methods that need to be executed, and I want to run some code after all of them have successfully completed. I am unable to modify or redefine the ajax methods. Can you please advise me on how to achieve this? I attempted to use WHEN b ...

Implementing Conditional Loops with $.each in AngularJS

I am working with an array called vm.settings.tab_permissions. Within this array, I need to check if the role is equal to vm.heading and replace it with vm.data. If the role is not equal, I want to push vm.data to vm.settings.tab. However, my current cod ...

The conversion of string to number is not getting displayed correctly when using console.log or document.write. Additionally, the concatenated display is also not functioning as intended

Being new to JS and HTML, this program was created to enhance my understanding of the concepts. I attempted a basic program to convert a string to a number in three different ways, but I am having trouble determining if the conversion actually took place. ...