如何使用axios将图像从VueJS上传到phpMyAdmin?

时间:2020-09-22 04:40:09

标签: php image vue.js axios

在我的owner.vue中,允许管理员将所有者添加到称为“所有者”的表中。目前,所有者的名称可以成功添加到数据库中,而图像的列则为空。我想让管理员能够将图像和所有者的名字一起添加到其中。

Owner.vue

//模板

<v-text-field v-model="ob_person_name" label="Owner name" outlined required></v-text-field>
<input type="file" ref="ob_personal_document">                    
<v-btn text @click="createContact()">Confirm</v-btn>

//脚本

<script>
    export default {    
       data: function () {
           return{
              ob_person_name:'',
              ob_acc_type:""
           }
       },
       methods: {
           createContact: function(){
              if(this.$refs.form.validate()){
                   this.ob_personal_document = this.$refs.ob_personal_document.files[0];
                   let formData = new FormData();
                   formData.append('ob_person_name', this.ob_person_name)
                   formData.append('ob_personal_document', this.ob_personal_document);

            var owner = {};
                 formData.forEach(function(value, key){
                 owner[key] = value;
            });

              this.axios({ 
                   method: 'post',
                   url: 'http://www.example.com/process.php?action=create',
                   data: formData,
                   config: { 
                       headers: {
                         'Content-Type': 
                         'multipart/form-data' 
                       }}
                   }).then(function (response) {
                       console.log(response)
                       this.newOwner.push(owner)
                   }).catch((error) => {
                       console.warn(error.message);
                   }) 
              }

     } 
</script>

process.php

<?php
$host = '111.22.222.111';
$dbname = 'test';
$username = 'username';
$password = "password";

$conn = mysqli_connect($host, $username, $password,$dbname);

// Check connection
    if (!$conn) {
        die("Connection failed!" .mysqli_connect_error());
    }

    $result = array('error'=>false);
    $action = '';

    if(isset($_GET['action'])){
        $action = $_GET['action'];
    }

    if($action == 'read'){
        $sql = $conn->query("SELECT * FROM owners");
        $owners = array();
        while($row = $sql->fetch_assoc()){
            array_push($owners, $row);
        }
        $result['owners'] = $owners;
    }

    if($action == 'create'){
          $ob_person_name= $_POST['ob_person_name'];
          $ob_personal_document = $_FILES['ob_personal_document'];

    $sql = $conn->query("INSERT INTO owners (ob_person_name, ob_personal_document)
    VALUES('$ob_person_name', '$ob_personal_document')");

    if($sql){
         $result['message'] = "Owner added successfully!";
    }
    else {
         $result['error'] = true;
         $result['message'] = "Failed to add owner";
    }
  }

phpMyAdmin中图像的结果显示为“ Array”,如下图所示。

the outcome of the ob_personal_document

1 个答案:

答案 0 :(得分:0)

我通过将图像发布到服务器的数据库并创建文件夹目录并创建了另一个file.php来解决了问题。

file.php

<?php
$ob_personal_document = $_FILES['ob_personal_document']['name'];
$valid_extensions = array("jpg","jpeg","png","pdf");
$extension = pathinfo($ob_personal_document, PATHINFO_EXTENSION);
if(in_array(strtolower($extension),$valid_extensions) ) {
   if(move_uploaded_file($_FILES['ob_personal_document']['tmp_name'], "uploads/".$ob_personal_document)){
      echo 1;
   }else{
      echo 0;
   }
}else{
   echo 0;
}
exit;

owner.vue

//模板

<input type="file" id="ob_personal_document" ref="ob_personal_document" />
<button type="button" @click='uploadFile()' >Upload file</button>

///在createContact之后添加另一个功能

uploadFile: function(){
       this.ob_personal_document = this.$refs.ob_personal_document.files[0];

       let formData = new FormData();
       formData.append('ob_personal_document', this.ob_personal_document);

       this.axios.post('file.php', formData,
       {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
       })
       .then(function (response) {

          if(!response.data){
             alert('File not uploaded.');
          }else{
             alert('File uploaded successfully.');
          }

       })
       .catch(function (error) {
           console.log(error);
       });

     },

在这种情况下,我还向phpMyAdmin列中添加了“图像”的名称,以获取与存储中图像名称相同的图像。