vue中使用minio上传文件

发布时间:2023年12月20日

创建一个 文件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) {
  }
}
文章来源:https://blog.csdn.net/wzwzwz555/article/details/135086844
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。