Vue+thinkphp5.1+axios to realize file upload

Vue+thinkphp5.1+axios to realize file upload

This article shares with you how to use thinkphp5.1 + Vue+axios to upload files for your reference. The specific content is as follows

Preface

Use thinkphp5.1 + Vue+axios+ to upload files

1. Page code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Upload Demo</title>
    <style>
        .fileBtn{
            width: 180px;
            height: 36px;
            line-height: 36px;
            background: skyblue;
            border-radius: 5px;
            display: block;
            text-align: center;
            color: white;
        }
        [v-cloak] {
            display: none;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
    <h1 v-cloak>{{message}}</h1>
    <form>
        <input type="file" name="file" ref="file" id="file" v-on:change="upload" style="visibility: hidden;" />
        <label for="file" class="fileBtn">Upload</label>
    </form>
</div>

</body>
</html>

<script>
    var vue = new Vue({
        el:'#app',
        data:{
            message:'File upload',
        },
        methods:{
            upload:function(file) {
                console.log(file.target.files[0]);
                var forms = new FormData()
                var configs = {
                    headers:{'Content-Type':'multipart/form-data; charse=UTF-8'}
                };
                forms.append('file',file.target.files[0]);
                axios.post('http://127.0.0.1/index/index/upload', forms,configs)
                    .then(function (response) {
                        if (response.data.code == 0) {
                            alert('File uploaded successfully');
                        } else {
                            alert('File upload failed');
                        }
                        file.target.value = '';

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

</script> 

2. Solve the problem of cross-domain interface

Apache 2.4.8 is used here. Find httpd.conf and add a line of configuration:

Header set Access-Control-Allow-Origin * 

3. Backend processing upload part

/**
     * File upload method verification*/
    public function upload()
    {
        try{
            $file = request()->file('file');

            if (empty($file)) {
                echo json_encode(['code' => 1,"msg" => 'Please select the upload file'],JSON_UNESCAPED_UNICODE);exit;
            }
            // Move to the framework application root directory /uploads/ directory $info = $file->move( '../uploads');
            if($info){
                // Get the upload information after successful upload // Output jpg
                echo json_encode(['code' => 0,"msg" => 'succcess'],JSON_UNESCAPED_UNICODE);exit;
            }else{
                // Upload failed to get error information echo json_encode(['code' => 1,"msg" => 'error'],JSON_UNESCAPED_UNICODE);exit;
            }
        } catch (Exception $e) {
            echo json_encode(['code' => 1,"msg" => 'error'],JSON_UNESCAPED_UNICODE);exit;
        }
}

4. Actual Effect

Test successful!

Regarding the learning tutorial of vue.js, please click on the special topics vue.js component learning tutorial and Vue.js front-end component learning tutorial for learning.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • PHP security attack and defense using file upload vulnerabilities and bypass techniques detailed
  • PHP case study on modifying the configuration of php.ini file upload size
  • php file upload to OSS and delete remote Alibaba Cloud OSS files
  • Analysis of phpcmsv9.0 arbitrary file upload vulnerability
  • Detailed explanation of the problem of uploading base64 encoded files in PHP
  • PHP implements file upload and download
  • PHP case analysis and solution for no file being uploaded

<<:  How to compile and install PHP and Nginx in Ubuntu environment

>>:  MySQL 8.0.12 Simple Installation Tutorial

Recommend

Methods and techniques for designing an interesting website (picture)

Have you ever encountered a situation where we hav...

How to use shell to perform batch operations on multiple servers

Table of contents SSH protocol SSH Connection pro...

Detailed graphic explanation of mysql query control statements

mysql query control statements Field deduplicatio...

Detailed tutorial for downloading and installing mysql8.0.21

Official website address: https://www.mysql.com/ ...

HTML tags: sub tag and sup tag

Today I will introduce two HTML tags that I don’t...

Execute initialization sql when docker mysql starts

1. Pull the Mysql image docker pull mysql:5.7 2. ...

Common rule priority issues of Nginx location

Table of contents 1. Location / Matching 2. Locat...

Summary of the differences between Mysql primary key and unique key

What is a primary key? A primary key is a column ...

Example analysis of mysql non-primary key self-increment usage

This article uses an example to illustrate the us...

Axios cancel request and avoid duplicate requests

Table of contents origin status quo Cancel reques...

7 interview questions about JS this, how many can you answer correctly

Preface In JavaScript, this is the function calli...

MySQL 5.7.20 zip installation tutorial

MySQL 5.7.20 zip installation, the specific conte...

How to install Jenkins on CentOS 8

To install Jenkins on CentOS 8, you need to use t...

Essential Handbook for Web Design 216 Web Safe Colors

The color presentation on a web page will be affec...