trogne
trogne

Reputation: 3552

sending a file with axios, without FormData api

I can send a file to the server using axios and the FormData api, like that :

    persist(avatar){
        let data = new FormData();
        data.append('avatar', avatar);
        axios.post(`/api/users/${this.user.name}/avatar`, data)
            .then(() => flash('Avatar uploaded!'));
    }

The avatar param, passed to persist(), is a file object from a form input of type "file".

I can then grab the file on the server side.

Is it possible to do it without using FormData ? That is, to simulate the FormData work ? Basically, I'm trying to understand the extra work done by the FormData api. Maybe it's not possible using axios, and I should do that with plain XMLHttpRequest.

Of course, simply sending the file object won't work :

axios.post(`/api/users/${this.user.name}/avatar`, {avatar: avatar})

On the server side, the avatar object will be empty. I can send metadata like avatar.name, but not the whole object.

Upvotes: 3

Views: 13491

Answers (1)

Seth Holladay
Seth Holladay

Reputation: 9539

Yes, it is possible to do the encoding manually on the client. Writing a form data encoder yourself may be useful if you really want to learn every little detail about how forms work. However, for most applications, I would not recommend it. The FormData API should be used in production.

You will need to refer to RFC 7578 for how to implement the encoder.

This specification defines the multipart/form-data media type, which can be used by a wide variety of applications and transported by a wide variety of protocols as a way of returning a set of values as the result of a user filling out a form.

More resources:

Upvotes: 2

Related Questions