vue+element上传图片到腾讯云

安装 cos-js-sdk-v5

npm install cos-js-sdk-v5

导入

import Cos from "cos-js-sdk-v5";
import cosKye from "@/utils/cos/key";
const cos = new Cos({
  SecretId: 'xxxxx-xxx', // 身份识别 ID   ( 腾讯云服务器密钥 )
  SecretKey: 'xxxxx-xxx', // 身份密钥
});
 <el-form>
	<el-form-item label="上传图片" prop="pass">
	   <el-upload
	     class="avatar-uploader"
	     :show-file-list="false"
	     action="https://jsonplaceholder.typicode.com/posts/"
	     list-type="picture-card"
	     :on-remove="handleRemove"
	     :on-change="beforeAvatarChange"
	     :auto-upload="true"
	     :before-upload="beforeAvatarUpload"
	     :on-success="handleAvatarSuccess"
	     :http-request="httprequest"
	   >
	     <img v-if="imageUrl" :src="imageUrl" class="avatar" />
	     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    </el-form-item>
  </el-form>



//js


	/**
     * 上传腾讯云
     */
    httprequest(res) {
      // 打印获得当前res的值.res.file就等于当前上传的对象
      console.log("httprequest-----------", res);
      // return
      cos.putObject(
        {
          Bucket: 'xxxxx-xxx' /* 存储桶: */,
          Region: 'xxxxx-xxx' /* 存储桶所在地域,必须字段 */,
          Key: "merchants/categories/" + res.file.name /* 必须是字符串  前面拼接存储桶文件名 */,
          StorageClass: "STANDARD", // 固定值
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度
            console.log("上传进度-------", JSON.stringify(progressData));
          },
        },
        (err, data) => {
          // 上传成功或者失败的回调
          console.log("腾讯云打印----------->>>>>>", err || data);
          // 默认显示的图片等于上传成功后的图片
          if (data) {
            this.imageUrl = "https://" + data.Location;
          } 
        }
      );
    },
    /**
     * 上传图片前判断
     */
    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG) {
        this.$message.error("上传分类图片只能是 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传分类图片大小不能超过 2MB!");
      }
      return isPNG && isLt2M;
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值