vue + minio上传文件服务器

1、安装依赖

npm install minio-js
npm install stream

2、vue组件中引入

import { Minio } from "minio-js";

3、初始化minio插件

initMinio() {
  this.minioClient = new Minio.Client({
    endPoint: 'xxx.xxx.x.xx', // MinIO服务器地址
    port: 59000, // 端口号
    useSSL: false, // 是否使用SSL
    accessKey: 'xxxxxxxxx', // 登录的accessKey
    secretKey: 'xxxxxxxxx', // secretKey  
});
}

4、上传逻辑

uploadFiles(options) {
  const stream = require("stream");
  const file = options["file"];
  const fileDate = new Date().getTime();
  let that = this;
  //判断储存桶是否存在
  this.minioClient.bucketExists(this.bucketName, (err) => {
    if (err) {
      if (err.code == "NoSuchBucket")
        return console.log("bucket does not exist.");
      return console.log(err);
    }
    //准备上传
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = (e) => {
      //读取完成触发,无论成功或失败
      const dataurl = e.target.result;
      //base64转blob
      const blob = that.toBlob(dataurl);
      //blob转arrayBuffer
      let reader2 = new FileReader();
      reader2.readAsArrayBuffer(blob);
      reader2.onload = (ex) => {
        //定义流
        let bufferStream = new stream.PassThrough();
        //将buffer写入

        bufferStream.end(Buffer.from(ex.target.result));
        //上传
        that.minioClient.putObject(
          this.bucketName,
          `test/${fileDate}${file.name}`,
          bufferStream,
          file.size,
          (err, etag) => {
            if (err == null) {
         that.
$message({message: '上传成功', type: 'success'});
         console.log('上传成功路径:',
`http://${this.ip}:${this.port}/${this.bucketName}/test/${fileDate}${file.name}`);
            }
          }
        );
      };
    };
  });
},
// 转blob格式
toBlob(base64Data) {
  let byteString = base64Data;
  if (base64Data.split(",")[0].indexOf("base64") >= 0) {
    byteString = window.atob(base64Data.split(",")[1]); // base64 解码
  } else {
    byteString = unescape(base64Data.split(",")[1]);
  }
  // 获取文件类型
  let mimeString = base64Data.split(";")[0].split(":")[1]; // mime类型
  let uintArr = new Uint8Array(byteString.length); // 创建视图

  for (let i = 0; i < byteString.length; i++) {
    uintArr[i] = byteString.charCodeAt(i);
  }
  // 生成blob
  const blob = new Blob([uintArr], {
    type: mimeString,
  });
  // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
  return blob;
},

5、vue中使用上传组件

<el-upload
  class="upload-demo"
  ref="upload"
  action="#"
  :show-file-list="false"
  multiple
  :http-request="uploadFiles"
>
  <el-button slot="trigger" size="mini" type="primary">打开多个文件</el-button>
</el-upload>

 

posted @ 2024-10-15 11:03  王浅浅  阅读(145)  评论(0编辑  收藏  举报