skip to Main Content

I have a list of URLs to images/videos. I want to show the file size along with the image on the website. I use regular img tag to render the image. Now, I need to show the size of the file as an additional detail.

I am using Angular and I tried the following:

this._httpGet(url, { responseType: 'blob' })

But it did not help. It gives unwanted results.

Can anyone please help me to achieve the same?

Thank you.

3

Answers


  1. Service to Fetch the Blob and Calculate Size: Create a service in Angular that uses HttpClient to fetch the resource as a Blob. Then, calculate the file size from this Blob.

    Displaying Image and Size in Component: Use the service in your component to fetch the size and display it alongside the image.

    Here’s a simple implementation:

    Step 1: Service Creation

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    @Injectable({
      providedIn: 'root'
    })
    export class FileSizeService {
    
      constructor(private http: HttpClient) { }
    
      fetchFileSize(url: string): Observable<number> {
        return this.http.get(url, { responseType: 'blob' }).pipe(
          map(blob => blob.size)
        );
      }
    }
    

    This service has a method fetchFileSize that makes an HTTP GET request to the provided URL and returns an Observable of the file size.

    Step 2: Component Implementation
    In your component, you can use this service to fetch the size for each URL and store it in a variable to be displayed in your template.

    import { Component, OnInit } from '@angular/core';
    import { FileSizeService } from './file-size.service';
    
    @Component({
      selector: 'app-image-display',
      template: `
        <div *ngFor="let item of imageUrlList">
          <img [src]="item.url" alt="image">
          <p>Size: {{item.size}} bytes</p>
        </div>
      `
    })
    export class ImageDisplayComponent implements OnInit {
      imageUrlList: Array<{ url: string, size?: number }> = [
        { url: 'https://example.com/image1.jpg' },
        // ... other URLs
      ];
    
      constructor(private fileSizeService: FileSizeService) { }
    
      ngOnInit() {
        this.imageUrlList.forEach(item => {
          this.fileSizeService.fetchFileSize(item.url).subscribe(size => {
            item.size = size;
          });
        });
      }
    }
    

    In this component, you have a list of image URLs. For each URL, the component calls fetchFileSize and updates the size in the imageUrlList.

    Login or Signup to reply.
  2. This will try to load the actual content to the client, you need to be aware of this. There is no way you will get the filesize of your content, without loading it to the client.

    You should consider for a server side solution, meaning that the server reads the filesize and returns it to the client.

    Login or Signup to reply.
  3. In Angular, you can use the following method to determine the file size of an image or video from a URL. The trick is to send a HEAD request to the server to obtain only the headers, including the "Content-Length" header, which indicates the size of the file.

      getFileSize(url: string): Promise<number> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    
        return this.http.head(url, { headers, observe: 'response', responseType: 'text' })
          .toPromise()
          .then(response => {
            const contentLength = response.headers.get('Content-Length');
            if (contentLength) {
              return parseInt(contentLength, 10);
            } else {
              throw new Error('Content-Length header not found');
            }
          })
          .catch(error => {
            console.error('Error fetching file size:', error);
            throw error;
          });
      }

    You can utilize this service in your component as follows:

    ngOnInit(): void {
        this.fileSizeService.getFileSize(this.imageUrl)
          .then(size => {
            console.log(size, '==>file size');
          })
          .catch(error => {
            console.error('Error:', error);
          });
      }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search