当前位置: 首页 > 工具软件 > leancloud-sdk > 使用案例 >

leancloud-storage-sdk初始化 base64上传图片

范峰
2023-12-01

 1、初始化sdk

import AV from "leancloud-storage"

AV.init({
  appId: "tBGTpuCzmDgW4KNgFS5dthcQ-gzGzoHsz",
  appKey: "QkhUqf2jRnME5pvHNmNezlIv",
  serverURL: "https://ejcadypa.lc-cn-n1-shared.com"
})

2、vue代码操作

<template>
  <el-upload class="avatar-uploader" :show-file-list="false" :on-success="handleAvatarSuccess"
    :http-request="handleUpload">
    <img v-if="imageUrl || ImgUrl" :src="imageUrl || ImgUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script >
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AV from "leancloud-storage"
export default {
  props: {
    ImgUrl: String
  },
  data() {

    return {
      imageUrl: ''
    }
  },
  methods: {
    // 使用getBase64处理图片
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    },
    handleUpload(obj) {
      this.getBase64(obj.file, (base64) => {
        const data = { base64: base64 };
        const file = new AV.File("pic.png", data); //将本地的base64转化为leancloud资源
        file.save().then(res => {
          let { url } = res.attributes
          console.log(url);
          this.imageUrl = url
          this.$emit("setimg", url)
        })
      })
    },
    handleAvatarSuccess(response, uploadFile) {
      // imageUrl.value = URL.createObjectURL()
      // console.log(uploadFile);/

    }
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

 类似资料: