user_id
user_id

Reputation: 47

PUT form-data axios vue.js

I just updated my User model with "avatar" field so I can upload a photo. I used a PUT method already configured and just added avatar to it. In postman the file upload (form-data) it works just fine, but when trying to upload it using axios from vue.js it doesn't work. I tried in many ways, the last one, I tried to send the request as multi form data.

async saveChanges() {
      const fd = new FormData();
      fd.append("id", this.$auth.user().id);
      fd.append("username", this.$auth.user().username);
      fd.append("email", this.user.email);
      fd.append("firstName", this.$auth.user().firstName);
      fd.append("lastName", this.$auth.user().lastName);
      fd.append("isAdmin", this.$auth.user().isAdmin);
      fd.append("password", this.user.password);
      fd.append("confirmpass", this.user.confirmpass);
      fd.append("avatar", this.selectedFile, this.selectedFile.name);
      fd.append("_method", "put");
      try {
        await this.axios.put(`/users/${this.$auth.user().id}`, {
          fd
        }).then((res) => {
          console.log(res);
        });
      } catch (err) {
        console.error(err);
      }
}

After i choose the file, it is available, but I am unable to send it trough my method. Should i create another request just for updating the avatar or is it possible to solve this?

Upvotes: 2

Views: 8727

Answers (3)

Sanaulla
Sanaulla

Reputation: 1619

My previous wrong code that return empty result in $request->all()

let data = new FormData()
data.append('message', 'AnyMessage')

Then I change it as follows and it's working fine -

let data = "message=AnyMessage"

Upvotes: 0

Jasim Juwel
Jasim Juwel

Reputation: 766

Pass your method as post method and define put in form data formData.append('_method', 'PUT') .

async handleSubmit() {

      let formData = new FormData();
      formData.append('image', this.file);
      formData.append('title', this.form.title);
      formData.append('_method', 'PUT')

      try {
        const response = await axios.post(`image-update/${this.$route.params.id}`, formData)

        this.$router.push('/');
        console.log(response);
      } catch (e) {
        this.error = 'Something error found !';
      }
    }

Upvotes: 5

Alexander Rogovoy
Alexander Rogovoy

Reputation: 56

Try this

axios.put('/users/${this.$auth.user().id', fd, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Upvotes: 4

Related Questions