user776490
user776490

Reputation: 115

How to send the content of v-file-input?

My component is something like this:

<template>
  <div>
    <v-file-input accept="image/*" v-model="image"></v-file-input>
    <button @click="uploadImage">Upload</button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      image: null
    }
  },
  methods: {
    async uploadImage(){
      await this.$axios.put('url', {image: this.image})
    }
  }
}
</script>

If I click the button and send the request, the request payload is {image: {}}. Why? How to send the content of this.image?

Upvotes: 3

Views: 7526

Answers (3)

Adam Muse
Adam Muse

Reputation: 1

here try this code pen i made codepen v-file-input

        addImage (file) {
        if (file) {
    const reader = new FileReader()

    reader.onload = (e) => {
      const imgObj = new Image()
      // console.log(e.target.result)
      imgObj.src = e.target.result
      // console.log(imgObj)
      this.imageHandler = imgObj
    }
    if (file) {
      reader.readAsDataURL(file)
    }
   } else {
    console.log('error')
  }
  }

major take aways:

const reader = new FileReader()

const imgObj = new Image()

imgObj.src = e.target.result

then reasign this.imageHandler = imgObj

Upvotes: 0

richxcame
richxcame

Reputation: 151

Just send file with FormData. You can put this code into uploadImage():

let form = new FormData();
form.append(file, this.file);
this.$axios.post('url', form)

And then U can access it in server.

Upvotes: 1

kissu
kissu

Reputation: 46824

You should probably use a POST rather than a PUT. But your code is working: if you console.log(this.image), you'll see the file, same goes for your Vue devtools in your browser.

I'm not sure how to see it in the network tab but this is properly sent to the given backend. I guess you just need a proper backend here.

This question may be useful here: How to see form data with enctype = "multipart/form-data" in Chrome debugger

Here is an MDN page talking about multipart/form-data objects even if there is no solution on how to see the actual payload neither: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Upvotes: 2

Related Questions