前端使用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
    },
相关推荐
一 乐1 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕1 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫1 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo2 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
北辰alk2 小时前
Vue 模板引擎深度解析:基于 HTML 的声明式渲染
vue.js
北辰alk2 小时前
Vue 自定义指令完全指南:定义与应用场景详解
vue.js
yinuo3 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
北辰alk3 小时前
Vue 动态路由完全指南:定义与参数获取详解
vue.js
北辰alk3 小时前
Vue Router 完全指南:作用与组件详解
vue.js
北辰alk3 小时前
Vue 中使用 this 的完整指南与注意事项
vue.js