前端上传图片单文件到七牛云组件

10次阅读

共计 2023 个字符,预计需要花费 6 分钟才能阅读完成。

图片上传流程:
1. 创建七牛云存储空间
2. 后台创建 token
3. 前端携带从后台获取的 token 上传图片到七牛云,成功后将返回 src 保存到数据库.

一、七牛云存储空间的创建需要先注册账号通过验证即可,创建好之后可以得到一对密钥

在文件管理页面得到一个外链地址

密钥是服务端用于生成 token 用的,外链用于前端。

二、后台创建 token

这里使用的 nodejs 的 koa 框架,封装成一个接口 getToken.js,在路由中使用它,当然要先安装七牛 npm install qiniu

服务端代码:

const router = require('koa-router')()
const qiniu = require('qiniu')

const accessKey = "xxx" //     前面得到的密钥
const secretKey = "xxx"
const bucket = "xxx" // 空间名

router.get('/', async (ctx) => {let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  let options = {
      scope: bucket,
      expires: 3600 * 2 //token 过期时间 2 小时
  };
  let putPolicy = new qiniu.rs.PutPolicy(options);
  let uploadToken = putPolicy.uploadToken(mac);

  if (uploadToken) {ctx.body = uploadToken} else {ctx.body = 'err'}
  
})


module.exports=router

前端代码也封装成了一个组件,因为需要新建和修改都使用同一个父组件,所以当不是新建时,父组件要传值给子组件,注意不要将 props 传值直接赋值给 src 属性,因为重传需要重新赋值,直接改 props 传值会有警告。

前端代码,uploadimage.js:

<template>
  <div class="upload">
    <el-upload class="avatar-uploader" 
      :action="upload" 
      :data="qiniuData"
      :show-file-list="false" 
      :headers="getAuthHeaders()" 
      :before-upload="beforeUpload"
      :on-success="handleSuccess">
      <img v-if="icon" :src="icon ? icon : imgUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
export default {
  props:{icon:{type:String}
  },
  data() {
    return {
      imageUrl:'',  // 传给后台的 src
      upload:'https://upload-z1.qiniup.com', // 七牛云的上传地址 (华北)
      qiniuData:{
        key:'', // 图片名字处理
        token:''
      },
      qiniuAddr:'http://xxx.clouddn.com' // 七牛云的图片外链地址
    };
  },
  mounted(){this.getQiniuToken()
  },
  methods: {handleSuccess(res) {this.imageUrl = `${this.qiniuAddr}/${res.key}`;
      this.$emit('getFromChild',this.imageUrl)
    },
    beforeUpload(file) {
      
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2; 
      if (!isJPG) {this.$message.error('上传头像图片只能是 JPG 格式!'); 
      } if (!isLt2M) {this.$message.error('上传头像图片大小不能超过 2MB!'); 
      }
      this.qiniuData.key = `upload_pic_${file.name}`

      return isJPG && isLt2M;   
    } ,
    async getQiniuToken(){const res=await this.$http.get('/uploadToken')
      this.qiniuData.token = res.data
    }

  }
}
</script>

前端代码,父组件部分代码:

<el-form-item label="图标">
   <uploadImage @getFromChild="getValue" :icon="model.icon"></uploadImage>
</el-form-item>

保存到数据库,另行请求接口这里不涉及。

参考:
七牛 SDK 官方
elementui

正文完
 0