Home > database >  Problem with uploading file Angular and Flask
Problem with uploading file Angular and Flask

Time:07-26

First of all excuse me if it's not well explained but I'll try my best. I'm trying to upload files from my front(Angular) and I'm having troubles with it. so far, this is my Service:

export class FileManagerService
{
    file: File = null;

    baseUrl: string = 'http://127.0.0.1:5000/';
    public addFile(file: File) {
            const formParams = new FormData();
            formParams.append('file', file.data);
            return this._httpClient.post(this.baseUrl   'upload', formParams);
    
        }

}

this is my component.ts :

onFilechange(event: any) {
        console.log(event.target.files[0]);
        this.file = event.target.files[0];
    }


    upload() {
        if (this.file) {
            this._fileManagerService.addFile(this.file).subscribe((resp) => {
            alert('Uploaded');
            });
        } else {
            alert('Please select a file first');
        }
        }

and this my component.html

<div >
                <!-- Upload button -->
                <button (click)="this.upload()"
                (change)="this.onFilechange($event)"
                type="file" id="formFile"
                    mat-flat-button
                    [color]="'primary'">
                    <mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                    <span >Upload file</span></button>
                    <input (change)="this.onFilechange($event)"  type="file" id="formFile">
</div>

okay so when I try uploading a file I get in my console BAD REQUEST enter image description here and the file is undefined enter image description here any help would be much appreciated, thank you!

CodePudding user response:

You have already grabbed file object and stored it inside this.file. Now while forming FormData, just pass the file object instead of file.data(which will be undefined)

formParams.append('file', file);

instead of

formParams.append('file', file.data);

CodePudding user response:

Thank you for your time, i found the issue. formData takes value a string and I put a file so I changed file:File to file:any and now the upload works !

  • Related