How do I send an image to a PHP API using VueJS?

旧街凉风 提交于 2021-02-11 15:02:31

问题


I am trying to send an object which contains an image using Vue to a PHP API but honestly I don't know how, I have my form

<form @submit='sendData'>
<div class="input-group">
     <label for="name">Name</label>
     <input type="text" @change="getText" name='text' id='text'>
  </div>
  <div class="input-group">
     <label for="photo">Photo</label>
     <input type="file" @change="getImage" name='photo' id='photo'>
  </div>
 </form>

export default{
data(){
  return {
myData:{
   text:'',
   photo:''
}
}
}

and the getImage() like this

getImage(event){
  let formData = new formData();
  formData.append('photo',event.target.files[0]);
  this.myData.photo=formData;
}
getText(event){
this.myData[event.target.name]=event.target.value;

}

sendData(event){
event.preventDefault();
this.$http.post('myapi/api/user',this.myData);
}

I don't know how to access this image in my PHP API and upload it to database. I tried accessing $_FILES but it's an empty array

Sorry seems the problem is that I am sending some other data too and not only the formData


回答1:


if you want to send an image to an api.

  1. You form should specify the type de data you must send for

    your form. you should add this.

     <form  enctype="multipart/form-data">
      <input type="text" class="form-control" v-model="myData.text" />
      <input type="file" class="form-control" @change="handleUpload($event.target.files)" />
     </form>
    

In your script you need to set this methods

 data () {
    return {
      myData: {
       text: '',
       photo: null
      }
     }
    },
    methods: {
        handleUpload(files) {
          this.myData.photo = files[0];
        },
       saveProductImage () {
          let formData = new FormData()
          formData.append('text', this.myData.text);
          formData.append('photo', this.myData.photo);

          // Send here
       }
    }

Please check the docs



来源:https://stackoverflow.com/questions/61858744/how-do-i-send-an-image-to-a-php-api-using-vuejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!