Home Web Front-end Vue.js How does vue+axios+php implement the file upload function?

How does vue+axios+php implement the file upload function?

Nov 06, 2020 pm 05:37 PM
axios php vue

How does vue+axios+php implement the file upload function?

Recommended: "PHP Video Tutorial"

When we are doing form submission, we often encounter some form submission requirements, then Will there be any different sparks after the axios of vue collides with the uploaded file? Listen to me one by one:

First of all, we need to write a form submission of axios of vue, because I use webpack, so code:

<template lang="pug">
  p
    input(type="file", ref="yin")
    button(@click="submit()") 点击上传
</template>
<script>
  export default{
    methods: {
      submit(){
        let formdata = new FormData();
        formdata.append(&#39;file&#39;, this.$refs.yin.files[0]);
        this.$axios({
          url: &#39;http://localhost/php/file_upload/file_updata.php&#39;,
          method: &#39;post&#39;,
          data: formdata,
        }).then((res) => {
          console.log(res.data)
        })
      }
    }
  }
</script>
Copy after login

Use the pug template, you can also change it to HTML, it’s harmless. It mainly depends on the js logic code. First declare a FormData object, and then pass the value in post. At this time The url is a PHP file I use in wamp. The file is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2017/11/23
 * Time: 10:57
 */
header("Access-Control-Allow-Origin:*");
// 响应类型
header(&#39;Access-Control-Allow-Methods:POST&#39;);
// 响应头设置
header(&#39;Access-Control-Allow-Headers:x-requested-with, content-type&#39;);
header("Content-type: text/html; charset=utf-8");
$file = $_FILES["file"];
if ($file["error"] > 0) {
    echo "错误:" . $file["error"];
} else {
    $name = iconv(&#39;utf-8&#39;, &#39;gb2312&#39;, "upload/" . $file["name"]);
    echo "文件名称:" . $file["name"] . "</br>";
    echo "文件类型:" . $file["type"] . "</br>";
    echo "文件大小:" . ($file["size"] / 1024) . "K</br>";
    echo "文件临时存储的位置:" . $file["tmp_name"] . "</br>";


    //保存上传的文件
    if (file_exists("upload" . $file["name"])) {
        echo $file["name"] . "文件已经存在";
    } else {
        //如果目录不存在则将该文件上传
        if (move_uploaded_file($file[&#39;tmp_name&#39;], $name)) {
            move_uploaded_file($file[&#39;tmp_name&#39;], "upload/" . $file["name"]);
        }
    }
}
Copy after login

 

Be sure to see the structure clearly, otherwise the uploaded file cannot be saved,

The header information in PHP solves the cross-domain problem and utf-8 transcoding solves the garbled problem, and then puts the obtained file into the upload folder;

is as follows:

Perfect

Related recommendations:

2020 Summary of front-end vue interview questions (with answers)

vue tutorial recommendation: 2020 latest 5 vue.js video tutorial selections

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How does vue+axios+php implement the file upload function?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to use vue pagination How to use vue pagination Apr 08, 2025 am 06:45 AM

Pagination is a technology that splits large data sets into small pages to improve performance and user experience. In Vue, you can use the following built-in method to paging: Calculate the total number of pages: totalPages() traversal page number: v-for directive to set the current page: currentPage Get the current page data: currentPageData()

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

How to use foreach loop in vue How to use foreach loop in vue Apr 08, 2025 am 06:33 AM

The foreach loop in Vue.js uses the v-for directive, which allows developers to iterate through each element in an array or object and perform specific operations on each element. The syntax is as follows: &lt;template&gt; &lt;ul&gt; &lt;li v-for=&quot;item in items&gt;&gt;{{ item }}&lt;/li&gt; &lt;/ul&gt; &lt;/template&gt;&am

See all articles