我有一个Vuejs组件的方法:
async submit () {
if (this.$refs.form.validate()) {
let formData = new FormData()
formData.append('userImage', this.avatarFile, this.avatarFile.name)
this.avatarFile = formData
try {
let response = await this.$axios.post('http://localhost:3003/api/test.php', {
avatar: this.avatarFile,
name: this.name,
gender: this.gender,
dob: this.DOB,
}, {
headers: {
'Content-Type': 'multipart/form-data; boundary=' + formData._boundary
}
})
if (response.status === 200 && response.data.status === 'success') {
console.log(this.response)
}
} catch (e) {
console.log(e)
}
}
}
在test.php
中,我使用json_decode(file_get_contents("php://input"), TRUE);
将数据作为$_POST
变量读取。
虽然我能够正确阅读name
,gender
和dob
,但我无法正确提取avatar
。
同样的解决方案?
注意:我没有将每个变量附加为formData.append(.., ..)
,因为我计划处理超过14个变量。
主持人请注意:我没有找到任何与其他数据对象一起使用formData的问题。
答案 0 :(得分:3)
所以,我用更简单的方式想出了这个:
let rawData = {
name: this.name,
gender: this.gender,
dob: this.dob
}
rawData = JSON.stringify(rawData)
let formData = new FormData()
formData.append('avatar', this.avatarFile, this.avatarFile.name)
formData.append('data', rawData)
try {
let response = await this.$axios.post('http://localhost:3003/api/test.php', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
test.php的:
$_POST = json_decode($_POST['data'],true);
注意:我可以选择使用:
Object.keys(rawData).map(e => {
formData.append(e, rawData[e])
})
但是因为我在rawData中处理嵌套对象(name: { first: '', last: ''} )
,所以我选择不这样做,因为它需要在客户端或服务器端使用递归方法。
答案 1 :(得分:0)
PHP (process.php)
<?php
$data = array(
"post" => $_POST,
"files" => $_FILES
);
echo json_encode($data);
?>
即插即用HTML
let vm = new Vue({
el: "#myApp",
data: {
form: {}
},
methods: {
submit: async function (e) {
e.preventDefault();
/* formData */
var formData = new FormData( this.$refs.formHTML );
/* AJAX request */
await axios({
method: "post",
url: "process.php",
data: formData,
config: { headers: { "Content-Type": "multipart/form-data" } }
})
/* handle success */
.then( response => { console.log(response.data); } )
/* handle error */
.catch( response => { console.log(response) } );
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
<div id="myApp" >
<form @submit="submit" ref="formHTML" >
Name: <input type="text" name="name" v-model="form.name" /><br />
Gender:
<input type="radio" name="gender" value="male" v-model="form.gender" /> Male
<input type="radio" name="gender" value="female" v-model="form.gender" /> Female <br />
File: <input type="file" name="upload" v-model="form.upload" /><hr />
<input type="submit" name="submit" value="Submit" />
</form>
</div>