user16001720
user16001720

Reputation:

Problem with uploading file Angular and Flask

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 class="mt-4 sm:mt-0">
                <!-- 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 class="ml-2 mr-1">Upload file</span></button>
                    <input (change)="this.onFilechange($event)" class="form-control" 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!

Upvotes: 0

Views: 147

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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 as any);

instead of

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

Upvotes: 0

Related Questions