What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component:

this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe(
  (data) => {
    console.log(data.messageHistoryBytes);
   let file = new Blob( [data.messageHistoryBytes] , { type: 'plain/text' });   
   let fileURL = URL.createObjectURL(file);
    window.open(fileURL);
  }
);

The code above successfully downloads a file in the browser. However, I would like to specify a name for the downloaded file, for example, download.csv. How can I achieve this?

Answer №1

One helpful trick is to generate a 'temporary' <a> element and then trigger a click event on it.

Give this a shot:

var downloadLink = document.createElement('a');
downloadLink.download = filename;
downloadLink.href = fileURL;
downloadLink.click();

Answer №2

Consider changing your

window.open(fileURL);

with:

 window.navigator.msSaveOrOpenBlob(file , "filename");

Answer №3

this.messageHistoryService.fetchMessageHistoriesCSV(msgHistoryRequest).subscribe(
  (response) => {

    console.log(response.data.messageHistoryBytes);

    let file = new Blob([response.data.messageHistoryBytes], { type: 'text/plain' });
    let fileURL = URL.createObjectURL(file);
    
    var linkToFile = document.createElement('a');
    linkToFile.download = "message-history.csv";
    linkToFile.href = fileURL;
    linkToFile.click();

    this.isSearchingInProgress = false;

  }

);

I made some changes to the code and it's working perfectly now.

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

Creating various functions for Joomla's AJAX component development

My component is currently working smoothly with AJAX and mootools. The view.raw.php file contains only one function called display. I've been attempting to add other functions within the component that can be accessed through AJAX, but have been facin ...

"Unable to move past the initial segment due to an ongoing

My portfolio webpage includes a "blob" and "blur" effect inspired by this YouTube video (https://www.youtube.com/watch?v=kySGqoU7X-s&t=46s). However, I am encountering an issue where the effect is only displayed in the first section of the page. Even a ...

What is the method for inserting the document URL into a text input?

Can someone provide guidance on grabbing the top URL and inserting it into a text input field? I've tried the following method, but it's not working. Any suggestions or ideas? Additionally, is there a way to make this text input field uneditable? ...

What is the best way to prevent automatic trimming in EJS variable assignment in Node.js?

When I attempt to write a variable from the database into an EJS table, it is being displayed with default trimming by the EJS template. However, I would like to display the variable from the database without any default trimming. I consulted the EJS temp ...

TypeScript failing to infer type from return value of class method

Currently, I am developing a class where the constructor calls one of its methods toJSON and sets the return value to an instance property: class Example { property; snapshot; constructor(){ this.property = 'property' if (Math.ran ...

Ways to transfer a function as attributes from one functional element to another?

I've encountered an issue when passing a function as a prop from one functional component (Dashboard) to another (Event). Every time I click the button on the child component that holds the passed function prop in the onClick value, it results in an e ...

Trigger animation when the scroll position reaches 0.52 in Next.js using framer-motion

I’m working on a landing page and I have a section where I’d like to create a simple opacity animation using framer-motion. The issue is that these animations typically trigger as soon as you land on the page, but I want them to be based on scroll pos ...

Gather image origins from a website, even if img tags are inserted through javascript or other methods during the page's rendering

I am looking to extract the URLs of all the images from a web page using C# and asp.net. Currently, I am utilizing: WebClient client = new WebClient(); string mainSource = client.DownloadString(URL); Afterwards, I am scanning the mainSource string for i ...

What steps can be taken to enable JSONIX to handle additional XML elements during the deserialization process?

JSONIX 2.0.12 is truly impressive. I am working with a substantial XML file and I am only looking to convert certain elements into JSON format. Whenever I omit some elements from my mapping file, JSONIX throws an unexpected element error during deseriali ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

What causes the "This page isn't responding" error to pop up in Edge and Chrome browsers while attempting to perform consecutive tasks in a web application built with Angular 8?

Trouble with Page Loading Whenever this error occurs, I find myself unable to perform any activities on that page. The only solution is to close the tab and open a new one. My current code allows me to navigate through an array list (Next and Previous) us ...

Using an image within the input group in Bootstrap 4

I'm a beginner in web development and I'm currently utilizing the glyphicon. This is how I'm currently using it: const className = `form-group ${touched && error ? 'has-danger' : ''}`; <div className={classN ...

Iterating through an array with conditional statements in JavaScript

I have recently joined this community and am new to coding. Unfortunately, I do not have anyone who can assist me with my issue. I have watched numerous YouTube videos in an attempt to solve the problem myself. I am working on looping through the array bel ...

Tips for smoothly animating and showing content as the user scrolls to a specific element on the page

Here is a sample template: <template> <div id="Test"> <transition name="fade"> <div class="row" id="RowOne"> <p>Lorem ipsum dolor odit qui sit?</p> </div> ...

The Process of Sending Values from app.js to a Vue File in Vue.js

My app.js is currently receiving a value called gtotal. I am trying to pass this value to the orderForm.vue file but am facing some difficulties in achieving this. require('./bootstrap'); window.Vue = require('vue'); window.EventBus ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

The ng-isolate-scope is not properly connected to the specified templateUrl

I am encountering difficulties when trying to implement isolated scope with templateUrl. Here is my directive test: beforeEach(ngModule('app.directives')); var scope, compile beforeEach(inject(function($rootScope, $compile){ scope = $ro ...

retrieving the smallest and largest values from a date range selector

I have been implementing a date range slider following the guidelines from this resource. I successfully set up the slider according to the documentation, but now I need to retrieve the minimum and maximum values as the slider is being moved. I attempted t ...

Trouble Connecting to Socket.io Event in MEAN Stack Application

On the server side: app.js let express = require('express'), app = express(), http = require('http').Server(app); io = require('socket.io')(http); http.listen(port, function () { ... }); io.on('connection ...

JavaScript form submission failing to transmit updated data

I have been working on a JavaScript function that changes the hidden value of a form based on which button is clicked, and then sends it via post to a processing page. Even though I have confirmed that the value is being changed correctly, when the post i ...