vue中使用minio上传文件

创建一个 文件getOssClient

import { getOssSetting } from "@/api/common";
import Vue from "vue";
import { getCookies, getLocal } from "@/utils/auth"; // get token from cookie
export async function getStsToken() {
  //从后台获取stsToken
  if (getCookies("token")) {
    const res = await getOssSetting();
    if (res.code == 200) {
      Vue.prototype.$ossClient = getClient(res.data);
    }
  }
 
}
export function getClient(data) {
  const Minio = require('minio');
let endpointes=data.endpoint.indexOf("//")>0?data.endpoint.substring(data.endpoint.indexOf('//')+2,data.endpoint.length):data.endpoint
let endpoints =endpointes.lastIndexOf(':')>0?endpointes.substring(0,endpointes.lastIndexOf(':')):endpointes
let port =Number(data.endpoint.lastIndexOf(':')>0?data.endpoint.substring(data.endpoint.lastIndexOf(':')+1,data.endpoint.length):80)
let minio={
  endPoint: endpoints,  //文件服务器地址
  port:port,//文件服务器端口
  useSSL: false,
  accessKey: data.accessKey,// 文件服务器账号
  secretKey: data.secretKey, // 文件服务器密码 
  bucket:data.bucketName, 
  sessionToken:data.securityToken,
  fileKey:data.fileKey
}
Vue.prototype.$minioInfo = minio;
const minioClient = new Minio.Client(minio)
  return minioClient;
}

getStsToken()

上传组件中使用 打开上传就会拿到key
在这里插入图片描述


 async handleUploadFile(e) {
      this.uploadArr.push(e);
      if (!this.btnLoading) {
        this.btnLoading = true;
        this.$emit("uploaded", true);
      }
      if (this.isUploading) {
        this.progressFlag = true
        this.loadProgress = 35
        this.isUploading = false;
        const upload = (e) => {
          uploadFile(e.file, e.file.name, this.$ossClient,this.$minioInfo)
            .then((res) => {
              
              this.loadProgress = 100
              this.progressFlag = false
              this.btnLoading = false;
              let newItem = this.addType({ ...res });
              
              this.previewImgList.push(newItem);
              this.isUploading = true;
              if (this.previewImgList.length < this.uploadArr.length) {
                let item = this.uploadArr[this.previewImgList.length];
                upload(item);
              } else {
                this.$emit("uploaded", false);
                this.btnLoading = false;
                this.$emit("uploadSuccess", this.previewImgList);
              }
              
            })
            .catch(() => {
              this.$emit("uploaded", false);
              this.btnLoading = false;
              this.isUploading = true;
              this.loadProgress = 0
              this.progressFlag = false
            });
        };
        upload(e);
      }
    },
// 上传文件
export function uploadFile(f , fileName, client,minioInfo) {
  try {
    let suffix = fileName.substr(fileName.lastIndexOf("."));
    let num = getNum(6, 10);
    let storeAs = suffix.substr(1) + "/" + new Date() * 1 + "/" + num + suffix;
      let reader = new FileReader();
      reader.readAsArrayBuffer(f);
      return new Promise((resolve, reject) => {
        reader.onload = function (e) {
          let res = e.target.result;//ArrayBuffer
          let buf = Buffer.from(res);//Buffer 
          const metaData = {
            'content-type': f.type,
            'content-length': f.size
          }
          return   client.putObject(minioInfo.bucket, storeAs, buf, f.size, metaData,function (err, data) {
            if (err){
              myMessage({
                message: err,
                type: "error",
                duration: 5 * 1000,
              });
            }else{
              let obj = {};
              obj.fileKey = storeAs;
              obj.originalName = fileName
              let urls=minioInfo.endPoint.indexOf("//")>0?minioInfo.endPoint:('http://'+minioInfo.endPoint)
              obj.url =  `${urls}:${minioInfo.port}/${minioInfo.bucket}/${storeAs}`;
              resolve(obj)
            }
          });
        }
      })
  } catch (e) {
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值