【问题标题】:How do I send an image to a PHP API using VueJS?如何使用 VueJS 将图像发送到 PHP API?
【发布时间】:2020-09-03 14:40:02
【问题描述】:

我正在尝试使用 Vue 将包含图像的对象发送到 PHP API,但老实说我不知道​​如何, 我有我的表格

<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:''
}
}
}

还有getImage() 这样的

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);
}

我不知道如何在我的 PHP API 中访问此图像并将其上传到数据库。 我尝试访问 $_FILES 但它是一个空数组

抱歉,问题似乎是我还发送了一些其他数据,而不仅仅是 formData

【问题讨论】:

    标签: php vue.js


    【解决方案1】:

    如果您想将 图像 发送到 api

    1. 你的表单应该指定你必须发送的数据类型

      你的表格。你应该添加这个。

       <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>
      

    在你的脚本中你需要设置这个方法

     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
           }
        }
    

    请查看docs

    【讨论】:

    • 很抱歉,因为我认为它不重要,所以我忽略了某些部分,但这是它不起作用的原因,如果你能帮助我,我会更新问题,我将不胜感激,抱歉为此
    猜你喜欢
    • 2014-08-23
    • 2022-01-25
    • 1970-01-01
    • 2014-02-05
    • 2014-10-17
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2013-02-04
    相关资源
    最近更新 更多