0

I have a need to post a single image and also multiple images. The way I post data is quite easy

var optionAxios = {
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
};
axios
    .post(
        "https://example.com/users/update_profile",
        {
            currency: this.currency,
            email: this.email,
            country: this.country,
            names: this.names,
            language: this.language,
            userid: this.$store.state.userid,
            telephone: this.telephone,
        },
        optionAxios
    )
    .then((response) => {})
    .catch(function (error) {
        console.log(error);
    });

I want to post a file and I was wondering if formData is the only available method I can attach single and multiple files in Axios.

The formData method

let formData = new FormData();
formData.append("file", this.file);

this.axios
    .post("http://localhost:8000/api.php", formData, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    })
    .then(function (response) {
        console.log(response.data);
    })
    .catch(function () {
        console.log("FAILURE!!");
    });

Would it be possible to attach a file or multiple files to post data without using formData?

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Gandalf
  • 1
  • 29
  • 94
  • 165
  • 1
    It appears it would be rather difficult to not use formdata https://stackoverflow.com/a/51560223/2073738 – Marcello B. Apr 09 '21 at 05:50
  • 1
    from a client perspective, you should not need to have host in your URL so you can post to your own proxy, and with [`multer`](https://github.com/expressjs/multer) you can easily get just one image or several including all other properties... and yes, it makes your work so much easier is you use `new FormData()` – balexandre Apr 09 '21 at 05:56
  • 2
    Does this answer your question? [sending a file with axios, without FormData api](https://stackoverflow.com/questions/51559445/sending-a-file-with-axios-without-formdata-api) – Mohammad Masoudi Apr 09 '21 at 10:49

0 Answers0