Vue.js cloud storage realizes image upload function

Time:2021-9-1

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 for storing massive files provided by Tencent cloud. It has the advantages of high scalability, low cost, reliability and security. Through console, API, SDK and tools, users can simply and quickly access cos, upload, download and manage multi format files, and realize massive data storage and management.

2、 Configure Tencent cloud cos

1. Import and storage

The code is as follows (example):
Objective: configure a Tencent cloud cos
Due to the particularity of class development, we don’t want to upload all the pictures to our own official server. Here we
A picture scheme of Tencent cloud can be adopted

在这里插入图片描述

The first step is to have a developer account of Tencent cloud

Real name authentication

在这里插入图片描述

Next, scan QR code authorization

在这里插入图片描述

Click to get free products

在这里插入图片描述

Select object store cos

在这里插入图片描述

At this step, the operation of the account is completed. Next, we need to create a bucket for storing pictures
Log in to the object storage console and create a bucket. Set the permissions of the storage bucket to public read and private write

Create bucket

在这里插入图片描述

Set CORS rules

在这里插入图片描述

Allowharder needs to be configured as *,
Here, our Tencent cloud storage bucket is set.

3、 New file upload component

Install JavaScript SDK


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

New upload picture 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 />
    </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', // key ID
  Secretkey: 'xxx' // key
}) // the instantiated package has the ability to upload to the bucket in the account
export default {
  data() {
    return {
      Filelist: [], // set the picture address as an array
      ShowDialog: false, // control the display of elastic layer
      imgUrl: '',
      currentImageUid: null,
      typeList: 'image/*',
      Showpercent: false, // show progress bar
      Percent: 0 // upload progress
    }
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    beforeUpload(file) {
      //File types allowed to upload
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        This. $message. Error ('uploaded pictures can only be in JPG, GIF, BMP, PNG format! ')
        Return false // return false will prevent the uploading of pictures
      }
      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) {
        //Perform upload operation
        cos.putObject({
          Bucket: 'xxx', // bucket
          Region: 'AP Nanjing', // Region
          Key: params.file.name, // file name
          Body: params.file, // file object to upload
          Storageclass: 'standard', // the uploaded mode type can directly default to the standard mode
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          //What should I do after data 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', / * region of storage bucket, required*/
        Key: file. Name / * required*/
      }, (err, data) => {
        // console.log(err || data)
      })
    },
    change(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

Detail page introduction components

<template>
  <div>
    <el-card>
      <el-tabs>
        < El tab panel label = "personal details" >
          <user-info />
        </el-tab-pane>
        < El tab panel label = "reset password" >
          <!--  Place 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 panel label = "department information" >
          <department />
        </el-tab-pane>
        < El tab panel 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. Because the currently written ‘view’ is a secondary navigation jump, it 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'
    }
  }]
}

在这里插入图片描述

design sketch

Click to view:

在这里插入图片描述

Select Avatar:

在这里插入图片描述

在这里插入图片描述

Check whether the cloud storage has been uploaded:

在这里插入图片描述

This is the end of this article about vue.js cloud storage’s image upload function. For more information about vue.js image upload, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

SuperMap GIS Service acceleration solution

###1. brief introductionSuperMapIn addition to generating a cache for the content requested by the user, the map cache produced in iserver can also be pushed to Iexpress through intelligent cache distribution. Therefore, the service request of the client can be directly responded by Iexpress, so as to improve the service efficiency.####1.1SuperMap acceleration scheme consists of […]