php - VueJS axios 上传图片
问题描述
我对 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
, 并以空值响应。
有什么我想念的吗?
解决方案
对不起大家,
我发现了问题,原来目标上传文件夹upload/
不是uploads/
感谢您的时间。
推荐阅读
- c# - 如何为 Playwright .NET 创建全局配置?
- java - 跨项目使用模块的最佳实践
- java - Java 无法识别我的 unicode 表情符号(错误:未知表情符号)
- python - PyEphem 从水平坐标返回不一致的赤经和赤纬
- sql-server - SSIS:多个源到一个目标表
- ansible - 无法通过 ansible playbook SSH 到远程主机
- java - org.postgresql.util.PSQLException: ERREUR: erreur de syntaxe sur ou près de « $2 » 位置:40
- r - Swap key and label in ggplot legend
- variations - 如何根据类似于 BAYC 或其他 NFT 收藏品的各种艺术资产以编程方式生成艺术变体?
- python - 我希望能够搜索我输入的名称并获得分数