deblockt / hal-rest-client

Typescript HAL Rest client
Apache License 2.0
25 stars 11 forks source link

Is it possible to upload the file during the Resource creation? #16

Closed EvgeniyReznichenko closed 7 years ago

EvgeniyReznichenko commented 7 years ago

Hello,

I'm wondering if it is possible to upload the file during the new Resource creation? e.g:

export class Avatar extends HalResource {

    @HalProperty()
    image: any; // <--- expect to handle the file

    @HalProperty()
    name: string;
}

On the HTML view lets assume we have something like that

<label>UploadAvatar</label>
<input class="form-control" type="file" (change)="onFileInputChange($event)">

TS method looks as below:

onFileInputChange(event) {
        if(event.target.files.length > 0) {
            let file = event.target.files[0];
            const resource = createResource(this.http.halClient, Avatar, "avatar/");
            resource.image = file;
            resource.name = 'Preview';
            resource.create();
        }
}

So this example works and the Ajax call is being made successfully, However the payload is incorrect since image field does not send the File but empty object: screenshot_1

At the same time if I'll do the same without using hal rest client (via native xhr), the request will be correct! e.g:

onFileInputChange1(event) {
        if(event.target.files.length > 0) {
            let formData = new FormData();
            formData.append('image', event.target.files[0]);
            formData.append('name', 'Preview');
            this.upload.sendFiles(this.http.apiUrl + '/avatar/', formData).subscribe((progress) => {
                console.log(progress);
            }, (error) => {
                console.log(error);
            });
        }
}

Network log: screenshot_2

deblockt commented 7 years ago

Sorry but hal-rest-client is done to manage HALResource. theimage field, is not an @HalProperty(), it can not be save with the rest of entity name field.

Hal only manage JSON format and not FormData, I don't think that is a good idea.

your /avatar endpoint is not a rest service.

You can look at this forum https://stackoverflow.com/questions/4083702/posting-a-file-and-associated-data-to-a-restful-webservice-preferably-as-json who have multiple solution to do a restfull service with image upload.