【发布时间】:2019-09-01 16:15:04
【问题描述】:
我在使用 axios 时遇到了一点问题。
我想上传一张图片到服务器,这是我的代码。
HTML 代码
<input type="file" id="file" ref="file" @change="onChangeFileUpload()"/>
<b-button type="submit" variant="success" class="float-left" @click="savePaiwei()">Save</b-button>
JS 代码
<script>
import axios from 'axios'
export default {
data(){
return{
file: ''
}
},
methods:{
savePaiwei(){
let formImage = new FormData();
formImage.append('file',this.file,this.file.name);
axios.post('http://xyxyx.com/api/upload.php',
formImage,
{
headers:{
'Content-Type': 'multipart/form-data'
}
}
}).then((response)=>{
console.log(response.data.name);
}).catch(function (error) {
console.log(error);
});
})
},
onChangeFileUpload(){
this.file = this.$refs.file.files[0];
}
}
}
</script>
PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: token, Content-Type');
header('Access-Control-Max-Age: 1728000');
die();
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>
但它只是无法上传图像。试图回显$target_file,它以空值响应。
有什么我想念的吗?
【问题讨论】: