前端使用miniO上传文件

项目背景:vue2,前提是请先安装miniO,若安装引入时报错,那就是版本不对,通常指定版本安装即可。

页面样式:

前端vue页面代码:

//<el-form>表单中:

              <el-form-item label="文件"  prop="fileIds">
                  <span v-if="showWait">文件上传中,请耐心等待</span>
                  <div v-else>
                    <div v-if="formUpload.urlIllustrate&&formUpload.typeFlag">
                      <input type="file" id="file" @change="uploadFile()" />
                      //实际只需要采纳文件上传输入框就行   其余代码是我的上传校验判断
                    </div>
                    <div @click="ruleUpInfo" v-else>
                      <span style="border:1px solid #000000;padding:4px;background- 
                       color:#EFEFEF;">选择文件</span>
                    </div>
                  </div>
                </el-form-item>

代码中引入minio,并声明配置mini连接

 import * as Minio from 'minio';
  let stream = require('stream')
  //连接minio文件服务器
  var minioClient = new Minio.Client({
    endPoint: 'xxxxxxxxxxxxxx.cn',
    accessKey: 'oooooooooooooo1',
    secretKey: 'cccccccccccccccccccccccc',
    useSSL: false,
    bucketName: 'nnnnnnnnnname' // 存储桶名称
  });

上传事件中:

  //上传文件
    uploadFile(fileObj,index) {
           let vm = this
          let file = document.getElementById('file').files[0];
          this.showWait=true //这是我自己的判断 可删
          console.log('fole',file);
          // 获取当前日期并格式化
          const now = new Date();
          const year = now.getFullYear();
          const month = (now.getMonth() + 1).toString().padStart(2, '0'); 
          const day = now.getDate().toString().padStart(2, '0');
          const formattedDate = `${year}-${month}-${day}`;
          //获取文件类型及大小
          const fileName = `${this.formUpload.typeFlag}/${formattedDate}/${file.name}`
         //文件名拼接日期和数据类型(此处是为了在minio库中看到日期对应的上传文件,所以拼接,按需使用。注意MiniO库中同名文件会被覆盖,所以建议最好加个日期或者定义数据类型之类的区分开)
          const mineType = file.type
          const fileSize = file.size
          //参数
          let metadata = {
            "content-type": mineType,
            "content-length": fileSize
          }
          //判断储存桶是否存在
            //这里nnnnnname改成配置的储存桶名称
          minioClient.bucketExists('nnnnnname', function(err) {
            if (err) {
              if (err.code == 'NoSuchBucket') return console.log("bucket does not 
          exist.")
              return console.log(err)
            }
            //存在
            console.log('Bucket exists.')
            //准备上传
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function (e) {//读取完成触发,无论成功或失败
              console.log('读取完成',e);
              const dataurl = e.target.result
              //base64转blob   这里调了下面toBlob方法,不要困惑vm是什么,我前面声明过vm=this 
             指向的哈
              const blob = vm.toBlob(dataurl)
              //blob转arrayBuffer
              let reader2 = new FileReader()
              reader2.readAsArrayBuffer(blob)

              reader2.onload = function(ex) {
                //定义流
                let bufferStream = new stream.PassThrough();
                //将buffer写入
                bufferStream.end(new Buffer(ex.target.result));
                //上传  
               //这里nnnnnname改成配置的储存桶名称
                minioClient.putObject('nnnnnname', fileName, bufferStream, fileSize,                                                     
               metadata, function(err, etag) {
                  console.log('走上传了',etag);
                  if (err == null) {
                     //这里nnnnnname改成配置的储存桶名称
                    minioClient.presignedGetObject('nnnnnname', fileName, 
                    24*60*60, function(err, presignedUrl) {
                      if (err) return console.log(err)
                      //输出url  上传到桶成功后会返回个地址
                      console.log('上传后0',presignedUrl)
                      if(presignedUrl){
                       vm.submitUpload(presignedUrl) //这里按需处理,我是拿到地址后,请求 
                       submitUpload方法,将地址传给后端存了的
                      }
                    })
                  }
                })
              }
            }
          })         
    },
    //base64转blob
    toBlob (base64Data) {
      let byteString = base64Data
      if (base64Data.split(',')[0].indexOf('base64') >= 0) {
        byteString = 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,可以直接使用
      return blob
    },
相关推荐
万物得其道者成6 分钟前
React Zustand状态管理库的使用
开发语言·javascript·ecmascript
小白小白从不日白7 分钟前
react hooks--useReducer
前端·javascript·react.js
下雪天的夏风19 分钟前
TS - tsconfig.json 和 tsconfig.node.json 的关系,如何在TS 中使用 JS 不报错
前端·javascript·typescript
青稞儿25 分钟前
面试题高频之token无感刷新(vue3+node.js)
vue.js·node.js
diygwcom31 分钟前
electron-updater实现electron全量版本更新
前端·javascript·electron
volodyan34 分钟前
electron react离线使用monaco-editor
javascript·react.js·electron
^^为欢几何^^43 分钟前
lodash中_.difference如何过滤数组
javascript·数据结构·算法
Hello-Mr.Wang1 小时前
vue3中开发引导页的方法
开发语言·前端·javascript
程序员凡尘1 小时前
完美解决 Array 方法 (map/filter/reduce) 不按预期工作 的正确解决方法,亲测有效!!!
前端·javascript·vue.js
编程零零七5 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql