Saving a file and other data to a database using Angular and Spring Boot

Discussão em 'Angular' iniciado por James Mwaura, Dezembro 3, 2024.

  1. James Mwaura

    James Mwaura Guest

    I'd like to save a file and other data to the database. After reading a lot I gather that this is very possible using both FormGroup and FormData. Could someone please look at my code and advise where I'm going wrong.

    my service

    imageUploadForm = new FormGroup({description: new FormControl(null)});
    formObj = this.imageUploadForm.value;
    data = JSON.stringify(this.formObj);

    public createImageFormData(productImage: ProductImage, imageFile: File): FormData {
    const formData = new FormData();
    formData.append('data', this.data);
    formData.append('name', imageFile.name);
    formData.append('imageFile', imageFile);

    new Response(formData).text().then(console.log) // only name of the image and the image are being appended
    return formData;
    }


    The template

    <form #newImageForm="ngForm" (ngSubmit)="onAddNewImage(newImageForm)">
    <div>
    <label>Description</label>
    <input
    name="description"
    id="description"
    class="form-control"
    placeholder="Enter description here"

    />
    </div>

    <div class="input-group mb-2">
    <div class="custom-file">
    <input
    multiple
    type="file"
    accept="image/*"
    name="location"
    (change)="onImageUrlChange($event)"
    class="custom-file-input"
    />
    <label class="custom-file-label"
    ><span [hidden]="!fileName">{{ fileName }}</span>
    </label>

    <img *ngFor='let url of images' [src]="url" height="150" width="200px" style="margin: 3px;"> <br/>
    </div>
    </div>

    <button mat-raised-button color="primary" type="submit">Save</button>
    </form>

    Continue reading...

Compartilhe esta Página