Search code examples
javascriptangularfileapi

Posting audio files from Angular assets to server


I'm not able to create a proper File object like below. Its creating an File object with size 0.

const file = new File([''], '../../assets/' + filename);
const formData: FormData = new FormData();
formData.append('file', file, 'filename.wav');
this.http.post('http://localhost:5000/api', 
    formData ).subscribe(data => {
      console.log('success', data);
    }, error => {
      console.log(error);
    });

Solution

  • I ended up creating a Blob first from the response of a XhrRequest, then converting it to a File object.

    sender.service.ts

    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    
    
    @Injectable()
    export class SenderService {
      postUrl = 'http://localhost:5000/post_url';
      fetchAudioUrl = 'http://localhost:4200/assets/';
    
      constructor(private http: HttpClient) {}
    
      send (audioFile: File) {
        const formData: FormData = new FormData();
        formData.append('file', audioFile, audioFile.name);
        return this.http.post(this.postUrl, formData);
      }
    
      getAudio (fileName: string) {
        return this.http.get(this.fetchAudioUrl + fileName, { responseType: 'blob'});
      }
    }
    

    demo.component.ts

    import { SenderService } from './sender.service';
    
    @Component({
    ......
      providers: [SenderService]
    })
    export class DemoComponent {
    
    constructor(private senderService: SenderService) {}
    
      buttonClicked(req: any): void {
        this.senderService.getAudio(req.fileName)
          .subscribe((data: any) => {
            const file = new File([data], req.fileName);
            this.senderService.send(file)
              .subscribe((data: any) => {
            console.log(data);
              }, error => {
                console.log(error);
              });
          });
      }