S
S
Sergei Abramov2020-05-02 12:56:08
Angular
Sergei Abramov, 2020-05-02 12:56:08

Why doesn't uploading files to the server work?

I crop a photo using ngx-image-cropper and try to send the crop to the server (PHP Yii2).
I found several lessons on the Internet, everywhere ± the same algorithm, but I see I'm missing something. So the component:

imageCropped(event: ImageCroppedEvent) {
        this.croppedImage = event.base64;
    }

    uploadAttachmentToServer() {
        const fileToUpload: File = new File([this.croppedImage], 'avatar.png');
        this.profileService.uploadAvatar(fileToUpload).subscribe(data => {
            console.log(data);
        }, error => {
            console.log(error);
        });
    }


This.croppedImage contains the cropped blob.
Service:

export const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'multipart/form-data',
    }),
    observe: 'response' as 'body',
};


    uploadAvatar(file: File): Observable<HttpResponse<any>> {
        const url = `${this.url}/avatar`;
        const formData: FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        return this.http.post<HttpResponse<any>>(url, file, httpOptions);
    }


In total, in the network we see that the request is gone, and the RequestPaylod shows the file data, something like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAKACAYAAAAMzckj...


But in PHP, the data does not come to the $_FILES variable as with the usual form submission mechanism, but to the request body. Of course, you can do some add-ons to get the file from the body, and not by the standard mechanism, but maybe there are more options? How can I make Angular send a file like normal ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergei Abramov, 2020-05-04
@PatriotSY

I figured it out, there are two errors:
1) I send not a form to the server, but a file, right, this is a typo:

return this.http.post<HttpResponse<any>>(url, formData, httpOptions);
// вместо
return this.http.post<HttpResponse<any>>(url, file, httpOptions);

2) The main reason is in Content-Type. When sending back from PHP, if you specify any, even empty, Content-Type, then the data will come in the php://input request body, without a header in $_FILES.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question