vue + minio上傳檔案伺服器

王浅浅發表於2024-10-15

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>

相關文章