Element avatar upload practice

Element avatar upload practice

This article uses the element official website and Qiniu Cloud official website

element-ui official website: https://element.eleme.io/#/zh-CN

Qiniu Cloud official website : https://www.qiniu.com/

1. After registering and logging in to Qiniu Cloud, you need to authenticate your real name

insert image description here

2. Enter the space management after entering the object storage

3. Create a new space

insert image description here

You can get the cdn test domain name here

Python SDK can be viewed in the developer center

To use Qiniu Cloud, you need to install it

pip install qiniu

We use the idea of ​​encapsulation for encapsulation

文件名:comm.py

# Qiniu Cloud from qiniu import Auth

# You need to fill in your Access Key and Secret Key
access_key = 'Access Key '
secret_key = 'Secret Key'

def qn_token():
    #Build authentication object q = Auth(access_key, secret_key)
    # The name of the space to be uploaded bucket_name = 'name'
    # Generate upload token
    token = q.upload_token(bucket_name)
    return token

Get the uploaded interface

# Import the packaged token
from utils.comm import qn_token

#Qiniu Cloud gets the token interface class GetQnToken(APIView):
    def get(self, request):
        token = qn_token()
        return Response({'code':200,'token':token})

With routing

from django.urls import path
from . import views 


urlpatterns = [
    path('gettoken/', views.GetQnToken.as_view())
]

After downloading element in vue, you can use the component

User avatar upload

<template>
    <div>
        <!-- action is a required parameter, the upload address is Qiniu Cloud: http://up-z1.qiniu.com/-->
        <!-- Additional parameters included when uploading data-->
        <!-- on-success Hook when the file is uploaded successfully-->
        <!-- before-upload is the hook before uploading files. The parameter is the uploaded file. If false is returned or Promise is returned and rejected, the upload is stopped. -->
        <el-upload
            class="avatar-uploader"
            action="http://up-z1.qiniu.com/"  
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :data='postData'>
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data() {
        return {
            imageUrl: '',
            postData:{
                // When uploading, you need to bring the attached token
                token:''
            }
        }
    },
    methods: {
        // Get Qiniu Cloud token
        getToken(){
            this.axios.get('sadmin/gettoken/').then(res=>{
                console.log(res.data)
                this.postData.token = res.data.token
            })
        },
        //Hook for successful file upload handleAvatarSuccess(res, file) {
            this.imageUrl = 'cdn test domain name' + res.key;
            console.log(this.imageUrl)
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('Uploaded avatar images can only be in JPG format!');
            }
            if (!isLt2M) {
            this.$message.error('The uploaded avatar image size cannot exceed 2MB!');
            }
            return isJPG && isLt2M;
        }
    },
    created() {
        this.getToken()
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

**Regional correspondence table of Qiniu Cloud storage objects**
**A storage area table of Qiniu**

| **Storage area** | **Region code** | Client upload address| **Server upload address** |
| ------------ | ------------ | --------------------------------- | ----------------------------- |
| East China | ECN | `http(s)://upload.qiniup.com` | `http(s)://up.qiniup.com` |
| North China | NCN | `http(s)://upload-z1.qiniup.com` | `http(s)://up-z1.qiniup.com` |
| South China | SCN | `http(s)://upload-z2.qiniup.com` | `http(s)://up-z2.qiniup.com` |
| North America | NA | `http(s)://upload-na0.qiniup.com` | `http(s)://up-na0.qiniup.com` |

This is the end of this article about the practical application of Element avatar uploading. For more relevant Element avatar uploading content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue.js+elementUI realizes the function of switching avatars by clicking left and right arrows (similar to the effect of carousel pictures)

<<:  MySQL concurrency control principle knowledge points

>>:  Extract specific file paths in folders based on Linux commands

Recommend

Detailed explanation of JavaScript Proxy object

Table of contents 1. What is Proxy? 2. How to use...

mysql5.6.zip format compressed version installation graphic tutorial

Preface: MySQL is a relational database managemen...

How does MySQL implement ACID transactions?

Preface Recently, during an interview, I was aske...

Essential Handbook for Web Design 216 Web Safe Colors

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

Html+css to achieve pure text and buttons with icons

This article summarizes the implementation method...

The three new indexes added in MySQL 8 are hidden, descending, and functions

Table of contents Hidden, descending, and functio...

Node.js+express+socket realizes online real-time multi-person chat room

This article shares the specific code of Node.js+...

A brief analysis of MySQL's lru linked list

1. Briefly describe the traditional LRU linked li...

Detailed explanation of mysql.user user table in Mysql

MySQL is a multi-user managed database that can a...

SQL function to merge a field together

Recently, I need to query all the fields in a rel...

JavaScript typing game

This article shares the specific code of JavaScri...

A brief talk about JavaScript variable promotion

Table of contents Preface 1. What variables are p...

Calling Baidu Map to obtain longitude and latitude in Vue

In the project, it is necessary to obtain the lat...

Detailed explanation of three ways to wrap text in el-table header

Table of contents Problem Description Rendering T...