【问题标题】:VueJS Axios upload imageVueJS axios 上传图片
【发布时间】: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,它以空值响应。

有什么我想念的吗?

【问题讨论】:

    标签: php vue.js axios


    【解决方案1】:

    对不起各位,

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

    感谢您的宝贵时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-30
      • 2019-03-26
      • 2021-03-10
      • 2021-01-29
      • 2017-09-22
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多