问题
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.
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