0

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!

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

7 Comments

I get this error //// (parameter) file: File Argument of type 'File' is not assignable to parameter of type 'string | Blob'. Type 'File' is missing the following properties from type 'Blob': arrayBuffer, slice, stream, textts(2345)
this is a ts problem i get this error in my VSCode
@Alex on which line it throws an error? formParams.append('file', file.data); this one?
yes that line when i changed file.data to file I get that error
I was trying to reproduce the error, but can not re-produce. Check this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.