How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to download that file. I am attempting to create a blob using AngularJS for this purpose, but the file is not being saved. Any suggestions?

ctrl.js

$scope.downloadFile = function(message){
        DitFactory.getFile(message).then(function(response){
            console.log('r',response);
            var blob = new Blob([ response ], { type : 'text/plain' });
            $scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
            console.log($scope.url);
        });
    };

serverResponse.json

{"level":"info","message":"another-2fdas  message"}

server.js

app.get('/file', function (req, res) {
    var dir = './ditLogs';
    var root = path.resolve('./ditLogs');
    var fileName = req.query.file_name;
    var data;
    fs.readdir(dir, function(err, items) {
        items.forEach(function(file){
            if(fileName === file){
                data = file;
                res.setHeader('Content-Disposition', 'attachment; filename=' + data);
                res.sendFile(data, {root: root});
            }
        });
    });
 });

Answer №1

When working with express, you may want to consider incorporating the following code snippet into your server.js file:

var filePath = 'path to your desired file';      
res.download(filePath, function(error){
    if(!error){
      console.log('Download prompt was successful');
      return;
    }
});

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

What is the best way to use a Handlebars file on multiple routes?

I have been working on extracting articles from a news website by scraping them successfully. The data is being displayed properly on the front-end console log, but I am facing an issue with rendering it onto the page using a button - it only appears when ...

Can Vue-router be used to load screens into Tabs?

In my setup, I have a routes file with multiple routes configured such as localhost:8000/test and localhost:8000/test2. My objective is to create a final route like localhost:8000/tabs, where I can utilize a tab library like bootstrap or Vuetify to displa ...

Issue with React component timer becoming unsynchronized with numeric input field

My number field and countdown timer are not staying synchronized. Even though I can start and pause the countdown, whenever I try to change the number value after pausing, the numbers get out of sync. The gap between the two values keeps growing as time p ...

Querying data with parameters in a client-side rendered application with Next.js

Currently, I am developing a chat application using Next.js and Axios. One of the functionalities I implemented is a dynamic route called chat/:pid to fetch data using the provided pid. However, I encountered an issue where the values are coming back as un ...

Learn the process of integrating VueJS with RequireJS

I am attempting to set up VueJS with RequireJS. Currently, I am using the following VueJS library: . Below is my configuration file for require: require.config({ baseUrl : "js", paths : { jquery : "libs/jquery-3.2.1.min", fullcalendar : "libs/ful ...

To ensure a rectangular image is displayed as a square, adjust its side length to match the width of the parent div dynamically

How can I make the images inside my centered flexbox parent div, #con, be a square with side length equal to the width of the parent div? The image-containing div (.block) is positioned between two text divs (#info and #links). I want the images to be squa ...

Tips on saving data in an AngularJS factory after receiving a response from another factory

IFactory.query( function (response) { $scope.type_content = response; $scope.showMenu = true; }, function (response) { $scope.message = "Error: " + response.status + " " + response.statusText; } ); $scope.saving = ...

A guide on extracting information from Cloud Firestore and converting it into a format that can be easily utilized on a local level using Cordova and Angular

In my Ionic/Cordova App, I am utilizing Cloud Firestore as the database to store and retrieve data. One challenge I am facing is extracting the stored information from Firestore and incorporating it into my calculation functions. The structure of my Fire ...

Designing a versatile pop-up window with jQuery or JavaScript that functions seamlessly across all web browsers

I've encountered an issue with my code where it displays a popup message correctly in Chrome, but when testing it on Firefox and Edge, it creates a strange box at the end of the page instead. Here is the code snippet I'm referring to: var iframe ...

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...

Selenium EventFiringWebDriver JavaScript: There is a SyntaxError due to a missing closing parenthesis after an argument in

Attempting to run a javaScript command through the EventFiringWebDriver class in Selenium. EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title=&ap ...

Struggling with inserting data into MongoDB within my MERN application

I am currently developing a MERN app that allows users to create tasks and collaborate with others. To start my backend, I ran the nodemon index.js command in the git bash terminal. However, every time I try to send POST requests for data, I encounter an e ...

nodemailer failed to authenticate login: 535 Authentication Error

I'm encountering a 535 Authentication Failed error when trying to utilize the nodemailer npm package in my node application for sending emails through the contact page. My email and password are correct, so I'm unsure why this issue is arising. v ...

Angular credit card filter with replacement

Looking for an easy method to display information in a credit card input field using angular1, such as: #### - #### - #### - #### ? Substitute the numbers with any symbols and insert "-" between every set of 4 numbers. ...

Is there a way to dynamically set the active panel of a JQuery Accordion when making a call?

Currently, I am faced with a scenario where I need to implement a greybox popup window using jQuery Accordion from the main page via links. I am curious to know if it is doable to specify a default active panel for the accordion when calling it. Below is ...

Which event in the listbox should I trigger to adjust the scroll position?

My webpage includes a listbox inside an update panel. I've managed to capture the scroll position, but now I'm facing difficulty in identifying the right javascript event to call my function for setting the scroll position after the update panel ...

The JSX component cannot use 'Router' as a valid element

Error Message The error message states that 'Router' cannot be used as a JSX component because its return type 'void' is not a valid JSX element. TS2786 import App from './App'; 5 | > 6 | ReactDOM.render(<Router ...

Unable to establish a connection with the Azure Knowledge Base generated by Language Studio and implement the provided code snippet:

const { ActionTypes } = require("botbuilder"); const { FAQMaker } = require("botbuilder-ai"); // Insert your own Azure Insight Base values here const insightBaseId = "**************************1d38"; const endpointToken = &qu ...

What are the steps to establish a connection with a MySQL database using an IP address other than "localhost"?

If I have a node js server running on my Raspberry Pi and a MySQL database hosted on my laptop, both connected to the same local area network (LAN). Laptop IP: 192.168.1.2 Raspberry Pi IP: 192.168.1.3 Step 1: How can I send data from the Raspberry Pi se ...

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...