preface

Recently, when I was doing projects, I needed to process pictures, tables, texts and other files in various formats to the database. It was cumbersome and troublesome to use traditional methods for processing, so I tried to use cloud storage and other methods to achieve this for the first time. After comparing aliyun and Tencent cloud and other websites, qiuniuyun is finally selected for actual combat. After successful registration and real-name authentication, qiuniuyun can use 10GB free storage space, which is relatively enough for use.


Register and use Seven Niuyun




1. Preparations After registration, real-name authentication is performed to obtain the AccessKey and SecretKey, which are used to invoke interfaces later.


2. Create storage space. Choose Management Console > Object Storage > Create Storage Space and fill in the corresponding information.

If you want users to have direct access to resources in any case, you can simply make the space public.

3. Personal center – Secret key view

For details, please refer to the official website of qiuniuyun

https://developer.qiniu.com/kodo/manual/1233/console-quickstart

4. Download seven Niuyun and introduce it into the project

The front reference

npm install qiniu-js    Copy the code

import * as qiniu from "qiniu-js"; // Reference in the fileCopy the code

Server reference

Create the qiniu.js file

const Router = require('koa-router')const qiniu = require('qiniu')letrouter = new Router(); // Upload tokenrouter.get('/qiniuToken',async(ctx)=>{    // ctx.body="This is the seven cows."    const accessKey = 'GVqmUaM71eMgmgEfm2lWBE8C2m6y3vbaeqNBCILm'    const secretKey = 'IA_gEbsUGSm-IqMzgM9odGVrX5IsdFLAAHSEPS2j'    const bucket ='class-online'    let mac = new qiniu.auth.digest.Mac(accessKey,secretKey);    let options={        scope:bucket,        expires:3600*24    };    let putPolicy = new qiniu.rs.PutPolicy(options);    letuploadToken = putPolicy.uploadToken(mac); ctx.body=uploadToken ? {code: 200, qiniuToken: uploadToken} {code: 400}}) / / get photo link and deposited in the database of the router. The post ('/getimgurl',async(ctx)=>{    let url = ctx.request.body.imgurl;    console.log("This is the URL."+url);    })module.exports = routerCopy the code

Index. Js file

// Introduce seven ox cloudslet qiniu = require("./adminApi/qiniu")

router.use('/qiniu',qiniu.routes())Copy the code

Front-end code performance

<template>
  <div>
    <el-upload
           class="upload-pic"
           list-type="picture"
           :action="domain"
           :data="QiniuData"
           :on-error="uploadError"
           :on-success="uploadSuccess"
           :before-upload="beforeAvatarUpload"
           :show-file-list="false"
          >
            <img v-if="imageurl" :src="imageurl" class="uploadavatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
  </div>
</template>
<script>
import url from ".. /.. /.. /serviceAPI.config"; // Depending on my situation, this is the file import axios from which I created the API collection myself"axios";
import * as qiniu from "qiniu-js";
export default {
 date() {return{
      QiniuData: {
        key: ""// Image name processing token:""}, domain:"http://upload.qiniup.com"// Qiniuaddr:""// Imageurl:""// Upload to uploadPicUrl:"",
      avatar_img: ""}}, // get qiniuyun Token when loading the pagemounted() { this.getQiniuToken(); }, methods:{// Decide the file format before uploading. BeforeAvatarUpload (file) {const isPNG = file.type ==="image/png";
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if(! isPNG && ! isJPEG && ! isJPG) { this.$message.error("Upload profile picture can only be JPG, PNG, JPEG!");
        return false;
      }
      if(! isLt2M) { this.$message.error("Upload profile picture size can not exceed 2MB!");
        return false;
      }
      this.QiniuData.key = `upload_pic_${file.name}`; }, uploadSuccess(response, file) { this.imageurl = URL.createObjectURL(file.raw); //imageurl is the front-end display image path this.uploadPicUrl = 'http://'${this.qiniuaddr}/${response.key}`; //uploadPicUrl uploadError(err, file) {this$message({
        message: "Upload error, please try again!".type: "error",
        center: true}); }, // Get seven niuyun TokengetQiniuToken() {
      axios({
        url: url.getQiniuToken,
        method: "get"}).then(response => { console.log(response); this.QiniuData.token = response.data.qiniuToken; }); }, // Submit data to the backgroundhandleSubmit() {
      axios({
        url: url.getimgurl,
        method: "post",
        data: {
          imgurl: this.uploadPicUrl,
          _id: sessionStorage.getItem("adminuser_id")
        }
      }).then(response => {
        if (response.data.code == 200) {
          let msg = response.data.message;
          this.$message.success(msg); }}); }}}; </script>Copy the code

Node back-end code

const Router = require('koa-router')
 const mongoose = require('mongoose')
 letrouter = new Router(); // Upload the generated and updated avatar link router.post('/getimgurl', async (ctx) => {
     let url = ctx.request.body.imgurl;
     let _id = ctx.request.body._id;

     const adminuser = mongoose.model("Adminuser")
     await adminuser.updateOne({
         _id: _id
     }, {
         $set: {
             avatar: url
         }
      }).exec().then(result=>{
         ctx.body={
            code:200, 
            message:'Update successful'
        }
    })
})

module.exports = router;Copy the code

According to the above way can basically achieve the required file upload to the seven niuyun object storage, get the URL back to the file, and then save the URL in the database, can greatly improve the performance of the site. If you have a problem, you can send a private message or communicate through your personal blog.