preface

In the actual development, because videos and pictures occupy a large space and the cost is relatively high to store on our own server, we can choose to store pictures and video resources on the third-party cloud storage (Qiuniuyun, Aliyun, Tencent Cloud, etc.), and only store the address on our own server.

Tencent Cloud COS application

1. Use the existing Tencent cloud service to create a free cloud storage (cloud.tencent.com/), create an account and authenticate with your real name.

2. Enable object storage

3. Create a storage bucket

4. In the bucket list, select the bucket and set the CORS rule (choose Security Management from the menu on the left). Because we are testing upload, all upload is allowed

5. Configure the cloud API secret key server belongs to the individual, requires certain permissions to upload pictures freely, this is responsible for permission verification is actually the secret key. Owning a secret key is essential for uploading.

Note: In actual work, the secret key is sensitive information and cannot be stored directly in the front end, which is easy to cause security problems. It is better to hand over the secret key to the back end for management. The front end obtains the secret key first by calling the interface, and then upload the secret key after it is available.

Picture uploading component

The Upload component based on elementUI implements image upload.

1. Encapsulate components in the SRC/Components /UploadImg folder

<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"// To specify the address where the file will be uploaded. Since we need to customize the upload action, set this to #:show-file-list="false"// Whether to display the list of uploaded files:before-upload="beforeAvatarUpload"// Check before uploading:http-request="upload"// Custom upload behavior (key) >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: ' '}},methods: {
    upload(file) {
      console.log(file)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if(! isPNG) {this.$message.error('Upload profile picture only in PNG format! ')}if(! isLt2M) {this.$message.error('Upload profile picture size cannot exceed 2MB! ')}return isPNG && isLt2M
    }
  }
}
</script>

<style>
.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>
Copy the code

2. Register globally in the SRC /components/index.js file

// omit other....
+ import UploadImg from '@/components/UploadImg'

// 1. Define plugins (extend Vue functionality)
const MyPlugin = {
  install(Vue) {
    // omit other....
 +   Vue.component(UploadImg.name, UploadImg)

  }
}
export default MyPlugin
Copy the code

3. Install dependencies

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

4. Instantiate the COS object in the global component under SRC/Components /UploadImg

// The following code is fixed
const COS = require('cos-js-sdk-v5')
// Fill in key and ID (key) in Tencent Cloud COS
const cos = new COS({
  SecretId: 'xxx'.// Identity ID
  SecretKey: 'xxx' // Identity key
})
Copy the code

SRC/Components /UploadImg upload with cos object (cos.putobjectAPI)

upload(res) {
  if (res.file) {
    // Perform the upload operation
    cos.putObject({
      Bucket: 'xxxxxx'./* Buckets */
      Region: 'xxxx'./* Specifies the location of the bucket. */ is a mandatory field
      Key: res.file.name, /* File name */
      StorageClass: 'STANDARD'.// Upload mode, standard mode
      Body: res.file // Upload the file object
    }, (err, data) = > {
      console.log(err || data)
      // Upload successfully
      if (data.statusCode === 200) {
        this.imageUrl = `https:${data.Location}`}}}})Copy the code

6. Add the upload progress bar in global components under SRC/Components /UploadImg. (1) Add a layout

<el-upload
  class="avatar-uploader"
  action="#"
  :show-file-list="false"
  :before-upload="beforeAvatarUpload"
  :http-request="upload"
>
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon" />increase<el-progress v-if="showProgress" :percentage="percentage" />
</el-upload>
Copy the code

(2) Supplementary data items

data () {
  return {
    // ...
    percentage: 0.// Upload progress
   isShow: false // Whether to display the progress bar}}Copy the code

(3) Update data item values

upload(res) {
  if (res.file) {
    // Displays a progress barincreasethis.isShow = true
    // Perform the upload operation
    cos.putObject({
      Bucket: 'xxx'./* Buckets */
      Region: 'ap-beijing'./* Specifies the location of the bucket. */ is a mandatory field
      Key: res.file.name, /* File name */
      StorageClass: 'STANDARD'.// Upload mode, standard mode
      Body: res.file, // Upload the file object
      onProgress: (progressData) = > {
        console.log(JSONStringify (progressData)) increasesthis.percentage = progressData.percentage * 100}},(err, data) = > {
        // Hide the progress barincreasethis.isShow = false
        console.log(err || data)
        if (data.statusCode === 200) {
           this.imageUrl = `https:${data.Location}`}}}})Copy the code

7. Use in the parent component

<upload-img v-model="imageUrl" />

V-model is a syntactic sugar equivalent to :value=”imageUrl” @input=”val=>imageUrl=val”.

8. Final code

<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :http-request="upload"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
  >increase<img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress
      v-if="isShow"
      :percentage="percentage"
    />
  </el-upload>

</template>


<script>
// The following code is fixed
const COS = require('cos-js-sdk-v5')
// Fill in key and ID (key) in Tencent Cloud COS
const cos = new COS({
  SecretId: 'xxx'.// Identity ID
  SecretKey: 'xxx' // Identity key
})
export default {
  name: 'UploadImg', adding props: {// The value of the V-model passed from the parent component
    value: { type: String.default: ' '}},data() {
    return {
      // imageUrl: '',
      percentage: 0.// Upload progress
      isShow: false // The progress bar is visible}},methods: {
    upload(res) {
      console.log('The current file to upload is', res.file)
      if (res.file) {
        // Perform the upload operation
        this.isShow = true // The progress bar is visible
        cos.putObject({
          Bucket: 'xxx'./* Buckets */
          Region: 'ap-nanjing'./* Specifies the location of the bucket. */ is a mandatory field
          Key: res.file.name, /* File name */
          StorageClass: 'STANDARD'.// Upload mode, standard mode
          Body: res.file, // Upload the file object
          onProgress: (progressData) = > {
            console.log('Upload file progress..... '.JSON.stringify(progressData))
            this.percentage = progressData.percentage * 100}},(err, data) = > {
          this.isShow = false // Progress bar is not visible
          console.log(err || data)
          // Upload successfully
          if (data.statusCode === 200) {
            const urlImg = `https://${data.Location}`increasethis.$emit('input', urlImg)
          }
        })
      },
     beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if(! isJPG) {this.$message.error('Upload profile picture in JPG format only! ')}if(! isLt2M) {this.$message.error('Upload profile picture size cannot exceed 2MB! ')}return isJPG && isLt2M
    }
    }
}
</script>

<style>
  .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>
Copy the code

The last

Hope to organize the information to help you, like the words please help to like

If you have any suggestions, feel free to leave them in the comments section

Please also criticize the inadequacies, thank you!