Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download files from assets using HttpClient in Angular?

Based on previous answers to similar questions such as this one, downloading, or in general, reading files from the assets directory should be a straightforward call to HttpClient's get method. For example if I have a DownloadService, I could simply define it as:

export class DownloadService {
    
  constructor(http: HttpClient){}

  download(data) {
    this.http.get('/assets/path/to/file.ext').subscribe(res => process(res));
  }

}

However, when I test this using ng serve, I get an error saying that /assets/path/to/file.ext is not a valid URL. I tried ./assets/path/to/file.ext, and assets/path/to/file.ext but I got the same error. Do I need to configure something in the runtime to get this working properly, or has this changed since those answers were written? I'm using Angular 9.

like image 610
Psycho Punch Avatar asked Aug 31 '25 05:08

Psycho Punch


1 Answers

This error occurs whenever you try to fetch something different than a JSON. To fix it, please define the responseType accordingly. For example

this.http.get('./assets/path/to/file.txt', {responseType: 'text'}).subscribe(res => process(res));

Also, please notice how I've changed the URL, it should be ./assets/foo.bar

Here's a working example https://stackblitz.com/edit/angular-9-starter-l1cn5j

Just check the console :)

By the way, these are the accepted types for responseType:

responseType: 'arraybuffer'|'blob'|'json'|'text'
like image 56
guzmanoj Avatar answered Sep 02 '25 20:09

guzmanoj