首页 > 解决方案 > 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, 并以空值响应。

有什么我想念的吗?

标签: phpvue.jsaxios

解决方案


对不起大家,

我发现了问题,原来目标上传文件夹upload/不是uploads/

感谢您的时间。


推荐阅读