Vue.js cloud storage realizes image upload function

Vue.js cloud storage realizes image upload function

Preface

Tip: The following is the main content of this article. The following cases can be used for reference

1. Object Storage

Cloud Object Storage (COS) is a distributed storage service provided by Tencent Cloud for storing massive files. It has the advantages of high scalability, low cost, reliability and security. Through a variety of methods such as console, API, SDK and tools, users can simply and quickly access COS to upload, download and manage files in multiple formats, and realize massive data storage and management.

2. Configure Tencent Cloud Cos

1. Import library

The code is as follows (example):
Goal: Configure a Tencent Cloud cos
Due to the particularity of class development, we do not want to upload all the pictures to our own official server. Here we can use a Tencent Cloud picture solution.

insert image description here

The first step is to have a Tencent Cloud developer account

Real-name authentication

insert image description here

Next, scan the QR code to authorize

insert image description here

Click here to get free products

insert image description here

Choose Object Storage COS

insert image description here

At this point, the account part is complete. Next, we need to create a bucket to store pictures. Log in to the object storage console and create a bucket. Set the bucket permissions to public read and private write

Create a bucket

insert image description here

Setting up CORS rules

insert image description here

AllowHeader needs to be set to *.
At this point, our Tencent Cloud storage bucket is set up.

3. Create a new file upload component

Installing the JavaScript SDK

npm i cos-js-sdk-v5 --save

Create a new upload image component src/components/ImageUpload/index.vue

For the upload component, we can use the el-upload component of element and adopt the photo wall mode listtype="picture-card"

<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="4"
      action="#"
      :file-list="fileList"
      :on-preview="preview"
      :http-request="upload"
      :on-change="change"
      :before-upload="beforeUpload"
      :accept="typeList"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showPercent"
      style="width: 180px"
      :percentage="percent"
    />
    <el-dialog title="Picture" :visible.sync="showDialog">
      <img :src="imgUrl" style="width: 100%" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'xxx', // secret id
  SecretKey: 'xxx' // secret key
}) // The instantiated package has the ability to upload and can be uploaded to the storage bucket in the account export default {
  data() {
    return {
      fileList: [], // Set the image address to an array showDialog: false, // Control the display of the pop-up layer imgUrl: '',
      currentImageUid: null,
      typeList: 'image/*',
      showPercent: false, // Whether to display the progress bar percent: 0 // Upload progress}
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    beforeUpload(file) {
      // File types allowed to be uploaded const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('Uploaded images can only be in JPG, GIF, BMP, or PNG formats!')
        return false // return false will prevent the image from being uploaded}
      const maxSize = 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('The maximum image size cannot exceed 1M')
        return false
      }
      this.currentImageUid = file.uid
      this.showPercent = true
      return true
    },
    upload(params) {
      // console.log(params.file)
      if (params.file) {
        // Execute upload operation cos.putObject({
          Bucket: 'xxx', // Storage bucket Region: 'ap-nanjing', // Region Key: params.file.name, // File name Body: params.file, // File object to upload StorageClass: 'STANDARD', // The upload mode type can be directly set to the standard mode by default onProgress: (progressData) => {
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          // How to process data after it is returned if (err) return
          this.fileList = this.fileList.map(item => {
            if (item.uid === this.currentImageUid) {
              return { url: 'http://' + data.Location, name: item.name }
            }
            return item
          })
          // console.log(this.fileList)
        })
      }
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      // console.log(file)
      cos.deleteObject({
        Bucket: 'xxx', /* Required*/
        Region: 'ap-nanjing', /* The region where the bucket is located, required field*/
        Key: file.name /* Required*/
      }, (err, data) => {
        // console.log(err || data)
      })
    },
    change(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

detail details page introduces components

<template>
  <div class="app-container">
    <el-card>
      <el-tabs>
        <el-tab-pane label="Personal details">
          <user-info />
        </el-tab-pane>
        <el-tab-pane label="Reset Password">
          <!-- Place the form -->
          <el-form
            label-width="120px"
            style="margin-left: 120px; margin-top: 30px"
          >
            <el-form-item label="Password:">
              <el-input style="width: 300px" type="password" />
            </el-form-item>
            <el-form-item label="Confirm Password:">
              <el-input style="width: 300px" type="password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary">Reset</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="Department Information">
          <department />
        </el-tab-pane>
        <el-tab-pane label="Select avatar">
          <image-upload />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script>
import userInfo from './component/Userinfo'
import department from './component/Department'
import imageUpload from '@/components/ImagUpload'

export default ({
  components:
   'user-info': userInfo,
   'department': department,
   'image-upload': imageUpload
  },
  // 
    methods: {
    upload(e) {
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = async function (e) {
        await upload({
          file: {
            originalname: '11.jpg',
            file: e.target.result
          }
        })
      }
    }
  }

})
</script>

Create a route for the detail page. Since the current 'view' is a secondary navigation jump, the route should be written as

import Layout from '@/layout'
export default {
  path: '/user',
  component: Layout,
  children: [{
    path: 'index',
    component: () => import('@/views/user/index'),
    name: 'user',
    meta: {
      title: 'User Management',
      icon: 'account'
    }
  },
  {
    path: 'detail',
    component: () => import('@/views/user/detail'),
    name: 'detail',
    hidden: true,
    meta: {
      title: 'User details',
      icon: 'account'
    }
  }]
}

insert image description here

Rendering

Click to view:

insert image description here

Select an avatar:

insert image description here

insert image description here

Check whether it has been uploaded to the cloud storage:

insert image description here

This is the end of this article about vue.js cloud storage to implement image upload function. For more related vue.js image upload content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

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
  • Problems encountered when uploading images using axios in Vue
  • Public multi-type attachment image upload area in Vue page and applicable folding panel (sample code)

<<:  How to compile and install xdebug in Ubuntu environment

>>:  MySQL 8.0.12 Installation and Usage Tutorial

Recommend

TypeScript learning notes: type narrowing

Table of contents Preface Type Inference Truth va...

JavaScript Advanced Programming: Variables and Scope

Table of contents 1. Original value and reference...

Vue uses OSS to upload pictures or attachments

Use OSS to upload pictures or attachments in vue ...

A brief analysis of HTML space code

How much do you know about HTML? If you are learni...

MySQL statement execution order and writing order example analysis

The complete syntax of the select statement is: S...

Vue implements seamless scrolling of lists

This article example shares the specific code of ...

MySQL Billions of Data Import, Export and Migration Notes

I have been taking a lot of MySQL notes recently,...

JS implements a detailed plan for the smooth version of the progress bar

The progress bar is not smooth I believe that mos...

WeChat applet realizes taking photos and selecting pictures from albums

This article shares the specific code for WeChat ...

Ten important questions for learning the basics of Javascript

Table of contents 1. What is Javascript? 2. What ...

React implements a highly adaptive virtual list

Table of contents Before transformation: After tr...

VUE+Canvas realizes the whole process of a simple Gobang game

Preface In terms of layout, Gobang is much simple...

Steps for restoring a single MySQL table

When I was taking a break, a phone call completel...