Problems encountered when uploading images using axios in Vue

Problems encountered when uploading images using axios in Vue

What is FormData?

After much searching and investigation, I learned that this magical thing is a new object added to XMLHttpRequest Level 2, which was proposed in February 2008. It can be used to submit forms and simulate form submission. Of course, the biggest advantage is that it can upload binary files and combine the name and value of all form elements into a queryString and submit it to the background.

Key point: You can combine the name and value of all form elements into a queryString and submit it to the backend. Isn't this what the backend calls converting the data format? Submit it according to the format. The separation of the front and back ends must be asynchronous submission, which can solve this problem very well!

It is also so easy to use. Just pass the form as a parameter to the FormData constructor!

A practical experience with the cooperation of vue and axios

<!--
    *. The upload component in the vue component I use here is buefy's vue component -->

<form method="post" enctype="multipart/form-data">
    <b-field class="file is-primary" :class="{'has-name': !!file}">
        <b-upload v-model="file" class="file-label" @input="getModifyAvatar()">
            <span class="file-cta">
                <b-icon class="file-icon" icon="upload"></b-icon>
                <span class="file-label">Click to upload</span>
            </span>
            <span class="file-name" v-if="file">
                {{ file.name }}
            </span>                    
       </b-upload>
   </b-field>
</form>

<script>
    export default {
        data(){
            return {
                userInfo: '', // Assign user related information to it through a get request file: null,
            }
        },
        methods: {
            // Modify avatar getModifyAvatar(){
                const formData = new FormData();
                //Construct formData data formData.append('avatar', this.file)
                // Submit put request getModifyInfo(formData).then(res => {
                    this.userInfo.avatar = res.data.avatar
                })
            },
        }
    }
</script>
// api.js
// This is my encapsulated global request method import { request } from '../network/request'

// Modify user avatar export const getModifyInfo = (params) => {
    return request({
        url: 've_register/1/',
        method: 'put',
        headers: { 'Content-Type': 'multipart/form-data' },
        data:params
    })
}

Looking at the above code, please note that you must set the request header when sending the request. As shown above, you also need to set enctype="multipart/form-data" in the HTML form, otherwise it will not work!

In the above examples, we have only used the append() method of FormData. Most of the articles about FormData on the Internet only mention the append() method. So what methods does the FormData object have? In fact, we can find out by just using the console:

After the console, we have a significant discovery. The FormData object has so many methods, so we still need to test it ourselves to find out the truth. The following will explain these methods one by one:

append()

The append() method is used to add key-value pairs to the FormData object:

fd.append('key1',"value1");
fd.append('key2',"value2");

fd is a FormData object, which can be a newly created empty object or one that already contains a form or other key-value pairs.

set()

Set the value corresponding to the key key value(s)

fd.set('key1',"value1");
fd.set('key2',"value2");

The append() method is somewhat similar. The difference between the two is that when the specified key value exists, the append() method adds all the newly added key-value pairs to the end, while the set() method will overwrite the previously set key-value pairs. Let's compare them with examples. We append() or set() new key-value pairs based on the previous form:

fd.append('name',"will");

There are two key-value pairs with key name:

The above is the difference between append() and set(). If the key value does not exist, the two have the same effect.

delete()

Receives a parameter, which indicates the name of the key value you want to delete. If there are multiple identical key values, they will be deleted together:

fd.append('name','will');
fd.delete('name');

The name information in the form and the name information added by append() are all deleted.

get() and getAll()

Receives a parameter, which indicates the name of the key to be searched, and returns the first value corresponding to the key. If there are multiple identical keys, all the values ​​corresponding to this key must be returned.

Also based on the above form:

fd.append('name','will');
console.log(fd.get('name')); // sean
fd.append('name','will');
console.log(fd.getAll('name')); // ["sean", "will"]

has()

This method also receives a parameter, which is also the name of the key, and returns a Boolean value used to determine whether the FormData object contains the key. Take the form above as an example:

console.log(fd.has('name')); // true
console.log(fd.has('Name')); // false

I won’t introduce the other ones. If you are interested, you can verify them yourself. Write them once, type them once, it is more practical than reading any article!

If the above article is helpful to you, please give our open source project a star: github.crmeb.net/u/xingfu Thank you very much!

The above is the details of the problems encountered by Vue using axios to upload pictures. For more information about Vue using axios to upload pictures, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Vue+SSM realizes the preview effect of picture upload
  • Implementation example of Vue+Element+Springboot image upload
  • Vue+axios sample code for uploading pictures and recognizing faces
  • Vue.js cloud storage realizes image upload function
  • Public multi-type attachment image upload area in Vue page and applicable folding panel (sample code)

<<:  Detailed explanation of multi-version concurrency control of large objects in MySQL

>>:  Detailed explanation of the specific use of the ENV instruction in Dockerfile

Recommend

CSS Back to Top Code Example

Most websites nowadays have long pages, some are ...

Complete steps to install Anaconda3 in Ubuntu environment

Table of contents Introduction to Anaconda 1. Dow...

Special commands in MySql database query

First: Installation of MySQL Download the MySQL s...

Mysql online recovery of undo table space actual combat record

1 Mysql5.6 1.1 Related parameters MySQL 5.6 adds ...

Basic operations of mysql learning notes table

Create Table create table table name create table...

Implementing search box function with search icon based on html css

Preface Let me share with you how to make a searc...

Front-end JavaScript housekeeper package.json

Table of contents 1. Required attributes 1. name ...

MySQL series multi-table join query 92 and 99 syntax examples detailed tutorial

Table of contents 1. Cartesian product phenomenon...

Summary of MySQL lock knowledge points

The concept of lock ①. Lock, in real life, is a t...

Detailed explanation of MySQL master-slave replication and read-write separation

Article mind map Why use master-slave replication...

MySql 8.0.11 installation and configuration tutorial

Official website address: https://dev.mysql.com/d...

Some tips on website design

In fact, we have been hearing a lot about web des...

How to restore a single database or table in MySQL and possible pitfalls

Preface: The most commonly used MySQL logical bac...