Angular Typescript convert file to string($byte)

Issue

I need to upload a file and send it as type $byte to the endpoint with POST method

First i am converting it to base64 and then from there to byte (i didn’t find anywhere that I can directly convert it to byte, so maybe my point here is wrong)

Code is in StackBlitz:
https://stackblitz.com/edit/angular-ivy-fya9mr?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

Thank you!

Solution

There’s no need to convert.

The values returned by the file input element’s files property are of type File, which is actually a binary Blob. You should be able to directly send it to the server as multipart form data:

saveImage(image: File): Observable<any> {
    const url = 'https://www.example.com/your-endpoint';

    const formData = new FormData();
    formData.append('image', image);

    return this.http.post<any>(url, formData);
}

Answered By – Robby Cornelissen

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.