VueJS Axios上传图片

时间:2019-04-11 05:47:59

标签: php vue.js 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,并且响应为空值。

有什么我想念的吗?

1 个答案:

答案 0 :(得分:0)

对不起,

我发现了问题,事实证明目标上传文件夹是upload/而不是uploads/

谢谢您的时间。