简体   繁体   中英

Upload file on the server through REST API

I'm trying to upload file on server through REST API. My api requests FormData model, but Im getting 400 bad request error.

payload from my request in devtools

------WebKitFormBoundaryvPiRGxMC3Ru3AoFA Content-Disposition: form-data; name="file"; filename="test.jpg" Content-Type: image/jpeg

------WebKitFormBoundaryvPiRGxMC3Ru3AoFA--

payload from my docs

file: (binary)

Just look some code below.

upload.component.html

<input type="file" accept="image/*" (change)="onFileChange($event)">

upload.component.ts

uploadForm = this._fb.group({
    profile: ['']
});
formData: FormData = new FormData();
...
onFileChange(event): void {
    if (event.target.files && event.target.files.length) {
        const file = event.target.files[0];
        this.uploadForm.get('profile').setValue(file);
    };
}
...
upload() {
    this.formData.append('file', this.uploadForm.get('profile').value);
    // API REQUEST
}

`

Is that the good way to change my input value to FormData ?

Can you please change your code from

this.formData.append('file', this.uploadForm.get('profile'.value);

to

this.formData.append('file', this.uploadForm.get('profile').value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM