Send Text Input to a Formdata (angular)

Asked

Viewed 26 times

0

I have an image upload form, but I also want to pass a text field next to the image, the api is working perfectly and when I send by Insomnia it creates everything right in the bank, but when making the requests in the frontend it only sends the image.

example of the service I am using

 importarArquivo(file:File, links: string ): Observable<HttpEvent<any>> {
    // instanciando formData para utilizar no req
    const formData: FormData = new FormData();

    formData.append('imagens', file);
     formData.append('links', links);



    const req = new HttpRequest('POST',`${environment.apiUrl}/banners`, formData );


    return this.http.request(req);
}

1 answer

0

First try to convert the file to Base4:

static converterArquivoParaBase64(file: File): Promise<string | ArrayBuffer> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

After this, in your request, send a json containing the file + properties you want:

salvar(link: string, base64File: string): Observable<HttpEvent<any>> {
   let parametros = {
            "imagem": base64File,
            "link": "wwww.imagem.com"
   }
   const req = new HttpRequest('POST',`${environment.apiUrl}/banners`, parametros);
   return this.http.request(req);
}

Obviously your backend should treat the Base64 file accordingly. Converting back to original file, saving to database or any other intention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.