node.js+vue上傳圖片到七牛雲

一、關於七牛雲

原文地址

註冊並實名認證爲標準用戶,可享受10GB的免費存儲。點擊註冊

1.註冊賬號並實名認證後,登錄開發者中心。

2.點擊對象存儲,新建存儲空間,會獲得一個測試的域名,但是不能配置。可以自定義自己的已備案域名,進行配置。

3.個人中心查看密鑰管理,備份AK,SK備用

4.可以在內容管理查看上傳的圖片。

二、node.js+vue上傳

1.node.js作爲服務器返回上傳token

這裏使用的是koa框架

router.get('/token',async function(ctx, next) {
    const accessKey = config.accessKey // 你的七牛的accessKey
     const secretKey = config.secretKey // 你的七牛的secretKey
     const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
     const options = {
      scope: config.scope // 你的七牛存儲對象
     }
     const putPolicy = new qiniu.rs.PutPolicy(options)
     const uploadToken = putPolicy.uploadToken(mac)
    ctx.body={
        uploadToken
    }})

2.vue使用element-ui的upload組件上傳圖片

//Upload.vue

<template>
    <div class="g-main"> 
       <img  :src="imageUrl" class="ablum">
        <el-upload
        class="photo-uploader"
        list-type="picture-card"
        :action= domain
        :http-request = upqiniu
        :before-upload="beforeUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
        <i class="el-icon-plus"></i> 
        </el-upload> 
         
        <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="imageUrl" alt="">
        </el-dialog>
        
    </div>
</template>

<script>
  export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        imageUrl: 'http://xxxxxx.cn/4.png',
        token: {},
        // 七牛雲的上傳地址,根據自己所在地區選擇,我這裏是華東區
        domain: 'https://upload-z0.qiniup.com',
        // 這是七牛雲空間的外鏈默認域名
        qiniuaddr: 'xxxxxxx.cn'
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.imageUrl = file.url;
        this.dialogVisible = true;
      },
       // 上傳文件到七牛雲
    upqiniu (req) {
      console.log(req)
      const config = {
        headers: {'Content-Type': 'multipart/form-data'}
      }
      let filetype = ''
      if (req.file.type === 'image/png') {
        filetype = 'png'
      } else {
        filetype = 'jpg'
      }
      // 重命名要上傳的文件
      const keyname = 'ablum'+Math.floor(Math.random() * 100) + '.' + filetype
      // 從後端獲取上傳憑證token
      this.axios.get('/api/api/token').then(res => {
        console.log(res)
        const formdata = new FormData()
        formdata.append('file', req.file)
        formdata.append('token', res.data.uploadToken)
        formdata.append('key', keyname)
        // 獲取到憑證之後再將文件上傳到七牛雲空間
        this.axios.post(this.domain, formdata, config).then(res => {
          this.imageUrl = 'http://' + this.qiniuaddr + '/' + res.data.key
          console.log(this.imageUrl)
        })
      })
    },
    // 驗證文件合法性
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上傳圖片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上傳圖片大小不能超過 2MB!')
      }
      return isJPG && isLt2M
    }
    }
  }
</script>

<style>
.g-main{
  position: relative;
  height: 100vh;
  width: 100%;
}
.ablum {
    display: block;
 height: 77vh;
 width: 100%;
object-fit:cover;
}
</style>