Vue.js cloud storage realizes image upload function



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”

      <i />
      style="width: 180px"
    < El dialog title = "picture": visible. Sync = "ShowDialog" >
      <img :src="imgUrl" style="width: 100%" alt="" />
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
          Bucket: 'xxx', // bucket
          Region: 'AP Nanjing', // Region
          Key:, // 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 = => {
            if (item.uid === this.currentImageUid) {
              return { url: 'http://' + data.Location, name: }
            return item
          // console.log(this.fileList)
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      // console.log(file)
        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

Detail page introduction components

        < El tab panel label = "personal details" >
          <user-info />
        < El tab panel label = "reset password" >
          <!--  Place form -- >
            style="margin-left: 120px; margin-top: 30px"
            < El form item label = "password:" >
              <el-input style="width: 300px" type="password" />
            < El form item label = "confirm password:" >
              <el-input style="width: 300px" type="password" />
              < El button type = "primary" > Reset < / El button >
        < El tab panel label = "department information" >
          <department />
        < El tab panel label = "select Avatar" >
          <image-upload />
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 =[0]
      const reader = new FileReader()
      reader.onload = async function (e) {
        await upload({
          file: {
            originalname: '11.jpg',


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 […]