Dev*_*wal 6 php vue.js vue-component axios nuxt.js
我有一个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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
在中test.php,我json_decode(file_get_contents("php://input"), TRUE);用来读取数据作为$_POST变量。
虽然我能读name,gender并dob正确,我不能获取avatar正常。
有相同的解决方案吗?
注意:formData.append(.., ..)由于我打算处理14个以上的变量,因此我不会附加每个变量。
主持人注意:在使用formData和其他数据对象一起使用时,我没有发现任何问题。
因此,我以一种更简单的方式解决了这个问题:
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'
}
})
Run Code Online (Sandbox Code Playgroud)
test.php:
$_POST = json_decode($_POST['data'],true);
Run Code Online (Sandbox Code Playgroud)
注意:我可以选择使用:
Object.keys(rawData).map(e => {
formData.append(e, rawData[e])
})
Run Code Online (Sandbox Code Playgroud)
但是由于我正在处理(name: { first: '', last: ''} )rawData中的嵌套对象,因此我选择不这样做,因为这将需要在客户端或服务器端使用递归方法。
| 归档时间: |
|
| 查看次数: |
7073 次 |
| 最近记录: |