在vue.js中上传照片和其他表单内容一起使用。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在vue.js中上传照片和其他表单内容一起使用。相关的知识,希望对你有一定的参考价值。

我有一个包含多个字段的表单,我将它们的内容发送到数据库,一切都很顺利。

现在,我想添加另一个字段来上传imageefile,并将其与表单中的其他字段一起发送,但我对如何做到这一点感到困惑。

我在我的表中创建了一个列,我想知道我应该在我的php文件和vue文件中添加什么。

vue.js文件:

    <template>
  <div class="book-table">
    <h1 class="text-light text-center bg-dark py-3">CRUD operations using VUE.JS</h1>
    <div class="container-fluid">
      <div class="d-flex justify-content-between">
        <h2 class="text-info">Books</h2>
        <button class="btn btn-info" @click="showAddModal=true">
          <i class="fas fa-user mr-2"></i>
          <span>add book</span>
        </button>
      </div>
      <hr class="bg-info">
      <div class="alert alert-success" v-if="successMsg">
        <span>{{ successMsg }}</span>
      </div>
      <div class="alert alert-danger" v-if="errorMsg">
        <span>{{ errorMsg }}</span>
      </div>
      <div class="row">
        <div class="col-lg-12">
          <div class="table-responsive">
            <table class="table table-bordered table-striped d-table ">
              <thead>
                <tr class="text-center text-light text-info bg-primary">
                  <th class="d-table-cell">ID</th>
                  <th>Cover</th>
                  <th>Title</th>
                  <th>Author</th>
                  <th>Price</th>
                  <th>Edit</th>
                  <th>Delete</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="book in books" :key="book.id" class="text-center">
                  <td> {{ book.id }} </td>
                  <td>
                    <img :src="Cover">
                  </td>
                  <td> {{ book.Title }} </td>
                  <td> {{ book.Author }} </td>
                  <td> {{ book.Price}} </td>
                  <td>
                    <a href="#" class="text-success" @click="showEditModal=true; selectBook(book);">
                      <i class="fas fa-edit"></i>
                    </a>
                  </td>
                  <td>
                    <a href="#" class="text-danger" @click="showDeleteModal=true; selectBook(book);">
                      <i class="fas fa-trash"></i>
                    </a>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <!-- ADD NEW BOOK -->
    <div id="overlay" v-show="showAddModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Add new book</h5>
            <button type="button" class="close" @click="showAddModal=false">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body p-4">
            <form method="post" action="#">
              <div class="form-group">
                <span>Title :</span>
                <input type="text" name="title" class="form-control mt-2" placeholder="name" v-model="newBook.Title">
              </div>
              <div class="form-group">
                <span>Author :</span>
                <input type="text" name="author" class="form-control mt-2" placeholder="author" v-model="newBook.Author">
              </div>
              <div class="form-group">
                <span>Price :</span>
                <input type="text" name="price" class="form-control mt-2" placeholder="price" v-model="newBook.Price">
              </div>
              <div class="form-group">
                <span>Cover :</span>
                <input type="file" ref="file" class="form-control mt-2" placeholder="cover">
              </div>
              <button class="btn btn-info btn-block" @click.prevent="showAddModal=false; addBook();">ADD</button>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- EDIT BOOK -->
    <div id="overlay" v-show="showEditModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Edit book</h5>
            <button type="button" class="close" @click="showEditModal=false">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body p-4">
            <form method="post" action="#">
              <div class="form-group">
                <span>Title :</span>
                <input type="text" name="title" class="form-control mt-2" v-model="currentBook.Title">
              </div>
              <div class="form-group">
                <span>Author :</span>
                <input type="text" name="author" class="form-control mt-2" v-model="currentBook.Author">
              </div>
              <div class="form-group">
                <span>Price :</span>
                <input type="text" name="price" class="form-control mt-2" v-model="currentBook.Price">
              </div>
              <div class="form-group">
                <span>Cover :</span>
                <input type="file" ref="file" class="form-control mt-2" placeholder="cover">
              </div>
              <div class="form-group">
                <button class="btn btn-info btn-block" @click.prevent="showEditModal=false; editBook();">EDIT</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- DELETE BOOK -->
    <div id="overlay" v-show="showDeleteModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Delete book</h5>
            <button type="button" class="close" @click="showDeleteModal=false">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body p-4">
            <h4 class="text-danger">Are you sure you want to delete this book ?</h4>
            <h6>You are deleting {{ currentBook.name }}</h6>
            <hr class="bg-info">
            <button class="btn btn-info btn-block" @click="showDeleteModal=false; deleteBook()">DELETE</button>
            <button class="btn btn-danger btn-block" @click="showDeleteModal=false">CANCEL</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "Homepage",
  data: function() {
    return {
      successMsg: false,
      errorMsg: false,
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      Cover: 'https://via.placeholder.com/150',
      books: [],
      newBook: { Title: "", Cover: "" , Author: "", Price: "" },
      currentBook: {}
    }
  },
  mounted: function() {
    this.getAllBooks();
  },
  methods: {
    getAllBooks() {
      axios.get('http://localhost/VUEJS/src/Backend/api.php?action=read')
        .then((res) => {
          if (res.data.error) {
            this.errorMsg = res.data.message;
          } else {
            this.books = res.data.books;
          }
        });
    },
    addBook() {
      var formData = this.toFormData(this.newBook);
      axios.post('http://localhost/VUEJS/src/Backend/api.php?action=create', formData,
      {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
       })
        .then((res) => {
          this.newBook = { Title: "", Cover: "", Author: "", Price: "" };
          if (res.data.error) {
            this.errorMsg = res.data.message;
          } else {
            this.successMsg = res.data.message;
            this.getAllBooks();
          }
        });
    },
    editBook() {
      var formData = this.toFormData(this.currentBook);
      axios.post('http://localhost/VUEJS/src/Backend/api.php?action=update', formData)
        .then((res) => {
          this.currentBook = {};
          if (res.data.error) {
            this.errorMsg = res.data.message;
          } else {
            this.successMsg = res.data.message;
            this.getAllBooks();
          }
        });
    },
    },
    toFormData(obj) {
      var fd = new FormData();
      for (var i in obj) {
        fd.append(i, obj[i]);
      }
      return fd;
    },
    selectBook(book) {
      this.currentBook = book;
    }
  }
}

</script>

php文件。

<?php

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST');
    header("Access-Control-Allow-Headers: X-Requested-With");

    $server= "localhost";
    $user= "root";
    $password= "";
    $dbname = "bookstore";
    $port= "3308";

    $conn = new mysqli($server,$user,$password,$dbname,$port);

    if($conn->connect_error){
        die("Connection Failed!, " .$conn->connect_error);
    }

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

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



    // FETCHING DATA FROM THE DB
    if($action == "read"){
        $sql = $conn->query("SELECT * FROM books");
        $book = array();
        while ($row = $sql->fetch_assoc()) {
            array_push($book, $row);
        }
        $result['books'] = $book;
    }



    // ADDING DATA TO THE DB
    if($action == "create"){
        $Title = $_POST['Title'];
        $Cover = $_POST['Cover'];
        $Author = $_POST['Author'];
        $Price = $_POST['Price'];

        $sql = $conn->query("INSERT INTO books (Title,Cover,Author,Price) VALUES('$Title',$Cover,'$Author','$Price')");

        if($sql){
            $result['message'] = "Book was added successfully!";
        }
        else{
            $result['error'] = true;
            $result['message'] = "Cannot add book! Maybe it's already exist";
        }
    }



    // UPDATING DATA
    if($action == "update"){
        $id = $_POST['id'];
        $Title = $_POST['Title'];
        $Cover = $_POST['Cover'];
        $Author = $_POST['Author'];
        $Price = $_POST['Price'];

        $sql = $conn->query("UPDATE books SET Title='$Title',Cover='$Cover',Author='$Author',Price='$Price' WHERE id='$id'");

        if($sql){
            $result['message'] = "Book was updated successfully!";
        }
        else{
            $result['error'] = true;
            $result['message'] = "Cannot update the book info!";
        }
    }



    // DELETING DATA
    if($action == "delete"){
        $id = $_POST['id'];

        $sql = $conn->query("DELETE FROM books WHERE id='$id'");

        if($sql){
            $result['message'] = "Book was deleted successfully!";
        }
        else{
            $result['error'] = true;
            $result['message'] = "Cannot delete this book!";
        }
    }


    echo json_encode($result);
    $conn->close();
?>

答案

看看这是否有帮助。

图片上传的工作实例 https:/picupload.netlify.app。

VueJS代码仓库 https:/github.commanojkmishradw_take5。

文件- https:/github.commanojkmishradw_take5blobmastersrccomponentsImageUploader.vue。

PHP[Laravel]部分可能对你的代码没有用, 它在防火墙后面, 所以不会工作. 下面是api的处理过程

public function imagesupload(Request $request){
       if (count($request->images)) {
        foreach ($request->images as $image) {
            $image->store('images');
        }
    }
    return response()->json(["message" => "Done"]);
 }

以上是关于在vue.js中上传照片和其他表单内容一起使用。的主要内容,如果未能解决你的问题,请参考以下文章

如何在 vue js 和 laravel 中使用外部脚本

Vue.js 项目部署

Jasny 与其他表单元素一起上传多个文件

如何自定义 Rails 上传表单并仍然显示已上传的文件

vue.js实战学习——表单与v-model

v-for 和 v-if 在 vue.js 中不能一起工作