A guide on how to retrieve images from a URL and save them using Blob in Angular 5

In my web application, I have a few links that lead to files with different content types - some are application/pdf and others are image/jpeg. When clicking on these links, the file should download or save based on their respective type.

While downloading PDFs works perfectly with the code below, I am facing an issue when trying to download images from a URL.

I have attempted to change the Content-Type and response type to image/jpeg, but unfortunately, it is not working as expected.

downloadDocFile(fileLocation, fileName) {

var fileNAme = fileName;
var url = fileLocation;

let headerD = this.service.getHeaderDict();

const headerDict = {
  'Content-Type': 'application/pdf',
  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
  'Access-Control-Allow-Headers': 'Authorization, X-Requested-With, Content-Type, Origin, Accept, X-clientid, X-locale, X-loggedin, X-version',
  'Access-Control-Allow-Credentials': true
}

const requestOptions = {
  headers: new Headers(headerDict), responseType: ResponseContentType.Blob
};

const proxyurl = "https://cors-anywhere.herokuapp.com/";

this.http.get(proxyurl +url,requestOptions).subscribe(
  res => {
    const data: Blob = new Blob([res.blob()], { type: 'application/pdf' });
    saveAs(data, fileNAme);
 })}

service.ts

getHeaderDict(): Object {
     return this.headerDict
}

Answer №1

  fetchAndSaveFile(file) {
    this.fileService.fetchAndSaveFile(file).subscribe(response => {
      let blob = new Blob([response]);
      
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        // Use msSaveOrOpenBlob for Internet Explorer
        window.navigator.msSaveOrOpenBlob(blob);
        return;
      }
      
      // For other browsers:
      const dataUrl = window.URL.createObjectURL(blob);
      let downloadLink = document.createElement('a');
      downloadLink.href = dataUrl;
      downloadLink.download = file.name;
      
      // Dispatch a click event on the link to trigger download
      downloadLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
    });
  }

Answer №2

Give this a shot,

this.http.get(proxyurl +url, {
  responseType: 'blob' as 'json',
  headers: new HttpHeaders().append('Content-Type', 'application/json')
}).subscribe(data => saveAs(data, fileNAme));

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 preventing my function from retrieving user input from an ngForm?

I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input. The "data" parameter in my submit function is the 'value' attribute of the ngForm. Fo ...

Ways to minimize the file size of an Angular2 project

Recently, I started exploring Angular 2 without any previous experience with Angular 1. I came across this tutorial https://angular.io/guide/quickstart and I'm wondering if there's a way to reduce the size of the project. After running 'npm ...

Combining Power BI with Spring Angular for Seamless Integration

I am in the process of building a web platform with Spring and Angular. One important element I want to include is Power Bi integration, allowing me to generate datasets and reports using Spring and display charts in Angular. Are there any resources or t ...

AngularJS 2 TypeScript structure

My application includes a user service for managing user operations and an interface for the user object. user.service.ts import {Injectable} from 'angular2/core'; export interface User { name: string; email?: string; picture?: string; } ...

Top method for changing classes in Angular

Within my Angular4 application, I've implemented a method to conditionally apply two classes as seen below: <some-element [ngClass]="{ 'fa-toggle-on': category.active, 'fa-toggle-off': !category.active }"> </some-element& ...

Why is the data from an Angular service returning as undefined when I call it from a component?

Currently, I'm utilizing the JSONPlace holder Fake API to retrieve data. Despite successfully fetching the data in my service, when I attempt to call that service from my app component, I am encountering an issue where it returns undefined. What could ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Troubleshooting Angular 2: Why Array Interpolation is Failing

Greetings everyone, I am diving into Angular 2 and attempting to create a basic Todo application. Unfortunately, I've hit a roadblock. My array interpolation seems to be malfunctioning. Any assistance would be greatly appreciated. Here is my AppCompo ...

Using Vue with TypeScript: A Necessary Prop

I recently utilized the vue-property-decorator to add a required prop to my component class. However, when I attempted to use the component without passing the prop, no console errors were displayed indicating that the required prop is missing. Why did thi ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...

What distinguishes ES6 from ES2015 in the TypeScript compiler option `--libs`?

Can you explain the distinction between ES6 and ES2015 in the TypeScript compiler option here? Also, what does --libs do? https://i.sstatic.net/iUv8t.png ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Unresolved promise: Issue encountered with StaticInjectorError within AppModule linking to HttpHeaders:

I am currently working on an ionic v3 project and facing a particular issue. The problem is similar to #47492475, even though I have already imported HttpClientModule in app.module.ts. Despite this import, the error continues to persist. Below are my .ts f ...

"Excel file becomes inaccessible after being downloaded from server using Lambda function with Node.js and Angular

My Nodejs code generates an excel file, which is then transformed based on client request. I am sending a request from an Angular frontend. The code utilizes exceljs to create the excel file. let [row] = await conn.execute( "Query& ...

Can you guide me on incorporating a date input with ngModel?

I have a date input field set up as follows: <input [(ngModel)]="value" type="text" class="form-control"> Can someone explain how I can display and submit the value correctly? The user's input should be formatted as dd/MM/yyyy, while t ...

Ensure your TypeScript class includes functionality to throw an error if the constructor parameter is passed as undefined

My class has multiple parameters, and a simplified version is displayed below: class data { ID: string; desp: string; constructor(con_ID:string,con_desp:string){ this.ID = con_ID; this.desp = con_desp; } } When I retrieve ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

A guide on simulating childprocess.exec in TypeScript

export function executeCommandPromise(file: string, command: string) { return new Promise((resolve, reject) => { exec(command, { cwd: `${file}` }, (error: ExecException | null, stdout: string, stderr: string) => { if (error) { con ...