首页 > 其他分享 >vite+vue3+minio

vite+vue3+minio

时间:2023-07-14 11:13:35浏览次数:41  
标签:const name vite vue3 date return VITE minio

之前h5用的minio上传文件,现在web端也需要用这个,但h5是用的vue2, web用的vue3,就出现了一些问题

 架子是用的vite搭建的,但vite不支持require导入。用import的话minio不支持import引入,也会报错

一. 用vue2搭个项目,将minio通过require方式导入,再进行导出, 上传npm,然后再npm install 打的包就可以使用了

  可以在项目里直接安装,已经打包好的minio

npm install tz-minio-upload_beta

 这样就安装上了

 

使用方法:

  新建一个minio.js, 里面存放实例和方法,不废话,上代码

 

import axios from 'axios'
import { createMinioClient, fileToStream } from 'tz-minio-upload_beta'
import Calendar from './calendar'   // 处理时间的文件,下面有

const { VITE_minio_BUCKET_NAME, VITE_minio_endPoint, VITE_minio_port, VITE_minio_accessKey, VITE_minio_secretKey } = import.meta.env    // 开发环境的配置

const minioClient = createMinioClient({
    endPoint: VITE_minio_endPoint, // 地址
    port: Number(VITE_minio_port), // 端口号,若地址为类似test.minio.com,就不必写端口号
    useSSL: false,
    accessKey: VITE_minio_accessKey,
    secretKey: VITE_minio_secretKey,
})

// 生成minio对象名
const createKey = (fileName) => {
    var random = Math.floor(1000000 + Math.random() * 9000000)
    return `${Calendar.format(new Date(), 'yyyy/MM/dd')}_${random}_web_${fileName}`
}

// minio对象上传
const minioDownload = (Key) => {
    return new Promise(resolve => {
        minioClient.getObject(VITE_minio_BUCKET_NAME, Key, (err,  result) => {
            if (err || result.statusCode != 200) {
                resolve(null)
                return
            }
            resolve(result.url)
        })
    })
}

// minio对象上传
export const minioUpload = ({
        name, // 文件
        file
    }) => {
    return new Promise(resolve => {
        const type = file.type
        const size = file.size
        // 参数
        const metadata = {
            'content-type': type,
            'content-length': size
        }
        minioClient.bucketExists(VITE_minio_BUCKET_NAME, function (err) {
            if (err) {
                if (err.code == 'NoSuchBucket') {
                    return console.log('bucket does not exist.')
                }
                return console.log(err)
            } else {
                console.log('bucket exist.')
            }
            fileToStream(file, (data) => {
                let buf = data._readableState.buffer.head.data
                minioClient.putObject(VITE_minio_BUCKET_NAME, name, buf, size, metadata, (err, data) => {
                        if (err) {
                            resolve(null)
                            return
                        }
                        resolve(data)
                    }
                )
            })
        })
    })
}

// 上传文件
export const uploadFiles = async (
    // 文件
    file
) => {
    // 1. 检查上传文件必填
    if (file === void 0) {
        console.error('上传文件不能为空')
        return null
    }

    // 2. 生成上传对象名称
    var { name, type, size } = file
    var Key = createKey(name)
    // var Key = name

    // 3. 上传minio对象
    var isUpload = await minioUpload({ name: Key, file })
    if (isUpload === null) {
        return null
    }
    // 4. 下载上传对象,获取url
    var filePath = await minioDownload(Key)
    if (filePath === null) {
        return null
    }
    return {filePath, name}   // 返回服务器图片路径和图片名称, 可以按你想要的返回
}

 

.env.dev文件

# 开发环境下的配置文件
VITE_ENV = 'dev'
# minio桶名称
VITE_minio_BUCKET_NAME = '桶名称'
# 地址
VITE_minio_endPoint = '172.***.***.***'
# 端口
VITE_minio_port = ****
# 登录的accessKey
VITE_minio_accessKey = '6kD27b6oDOuYzt2'
# 登录的secretKey
VITE_minio_secretKey = 'y5kVAt4ti2ytXHjl0AjB77vC3YVY7Yd'
calendar.js
const ONE_DAY = 24 * 60 * 60 * 1000

// 星期名称map
const CHINESE_WEEK_MAP = {
  0: '星期天',
  1: '星期一',
  2: '星期二',
  3: '星期三',
  4: '星期四',
  5: '星期五',
  6: '星期六'
}

// 时间段
const TIME_SPACING_CHINESE = [
  {
    time: [1, 5],
    name: '凌晨'
  },
  {
    time: [5, 8],
    name: '早上'
  },
  {
    time: [8, 11],
    name: '上午'
  },
  {
    time: [11, 13],
    name: '中午'
  },
  {
    time: [13, 17],
    name: '下午'
  },
  {
    time: [17, 19],
    name: '傍晚'
  },
  {
    time: [19, 23],
    name: '晚上'
  },
  {
    time: [23, 24],
    name: '子夜'
  },
  {
    time: [0, 1],
    name: '子夜'
  }
]

const calendar = {
  // 一天时间秒数
  ONE_DAY,
  // 获取时间对象,默认获取当天
  getDateInfo(date) {
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      day: date.getDate(),
      hour: date.getHours(),
      min: date.getMinutes(),
      second: date.getSeconds(),
      week: date.getDay()
    }
  },
  // 获取中文时间
  getDateChinese(date) {
    const result = this.getDateInfo(date)
    const timeInfo = TIME_SPACING_CHINESE.filter(item => {
      return result.hour >= item.time[0] && result.hour < item.time[1]
    })[0]
    return {
      ...result,
      weekChinses: CHINESE_WEEK_MAP[result.week],
      timeChinses: timeInfo.name
    }
  },
  // 格式化时间
  format(date, format) {
    var obj = this.getDateInfo(date)
    return format
      .replace('yyyy', this.prefixZero(obj.year))
      .replace('MM', this.prefixZero(obj.month))
      .replace('dd', this.prefixZero(obj.day))
      .replace('hh', this.prefixZero(obj.hour))
      .replace('mm', this.prefixZero(obj.min))
      .replace('ss', this.prefixZero(obj.second))
  },
  // 前置0
  prefixZero(value) {
    return Number(value) > 9 ? `${value}` : `0${value}`
  }
}

export default calendar

文件中使用:

  

<el-upload
        accept="image"
        class="avatar-uploader"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
>
         <img v-if="imageUrl" :src="imageUrl" class="avatar" />
         <el-icon v-else class="avatar-uploader-icon"><Plus />    
         </el-icon>
</el-upload>



<script>

import { uploadFiles } from '@/utils/minio.js'
const imageUrl = ref('')
// 上传头像 
const beforeAvatarUpload = async (val) => {
   // val是上传的文件 await uploadFiles(val).then( imgInfo => {
     // filePath是minio上传成功后返回的图片路径 const { filePath } = imgInfo formData.value.avatar = filePath imageUrl.value = filePath }) } </script>

这样就能拿到上传后的图片路径了,显示或者放到参数里都可以了

 

方法二

  使用大佬的minio-js, 开源地址

 

  

标签:const,name,vite,vue3,date,return,VITE,minio
From: https://www.cnblogs.com/alannero/p/17552973.html

相关文章

  • Vue3+Vue-Router+TypeScript+Vite+Element-Plus+Axios+Pinia快速搭建开发框架
    1、环境准备(1)首先你得需要安装node和npm2、环境初始化(1)先随意找个文件夹,初始化vite#安装pnpmnpmi-gpnpm#初始化vitepnpmcreatevite#安装依赖pnpminstall(2)最后我们执行pnpmrundev3、安装插件(1)Eslint校验代码工具安装eslint#安装eslint......
  • 使用vue3、egg和SQLite开发通用管理后台系统
    使用vue3、egg和SQLite开发通用管理后台系统plaform是一个基于RBAC模型开发的后台管理系统,没有多余的功能。本项目是一个以学习为目的的后台项目,旨在让前端也能充分了解RBAC模型是如何设计的,不建议用于线上,因为未经过充分的测试。项目地址:https://github.com/essay-org/platform......
  • Vue3
    一、创建Vue3.0工程1.使用vue-cli创建官方文档:https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create##查看@vue/cli版本,确保@vue/cli版本在4.5.0以上vue--version##安装或者升级你的@vue/clinpminstall-g@vue/cli##创建vuecreatevue_test##......
  • minio 配置https访问
    官网文档:https://docs.min.io/docs/how-to-secure-access-to-minio-server-with-tls.html在${HOME}.minio/certs文件夹下1、生成私钥opensslgenrsa-outprivate.key20482、生成自签名证书创建一个以openssl.conf以下内容命名的文件。设置IP.1和/或DNS.1指向正确的IP/DNS......
  • nginx部署 vue3 同时 配置接口代理(详细)
    Vue项目配置.env文件在项目根目录下创建文件夹(.env.production)##.env.production生产环境配置VUE_APP_SYS_URL=sysapi##nginx需要用的的代理表示VUE_APP_MODE=product##模式baseUrl使用VUE_APP_SYS_URL变量代替Nginx下载部署和配置api代理Nginx下载......
  • vue+vite项目在浏览器运行正常,在钉钉白屏报错,在嵌入的app里面白屏报错
    1.在钉钉直接打开本地跑的项目白屏并且报错UncaughtReferenceError:globalThisisnotdefined/@vite/client:135:7ReferenceError:globalThisisnotdefinedathttp://192.168.20.36:5173/@vite/client:135:7UncaughtSyntaxError:Unexpectedtoken./src/main.ts:19:38......
  • vue3核心概念-Mutation-辅助函数
    你可以在组件中使用 this.$store.commit('xxx') 提交mutation,或者使用 mapMutations 辅助函数将组件中的methods映射为 store.commit 调用(需要在根节点注入 store)辅助函数只能在选项式API中使用<template><h3>Nums</h3><p>{{getCount}}</p><inputtype="......
  • vue3 图片懒加载
    使用vue第三方库useIntersectionObserver创建文件directives/index.js导入第三方库import{useIntersectionObserver}from'@vueuse/core'exportconstlazyPlugin={install(app){app.directive('img-lazy',{mounted(el,binding){......
  • Vue3 实现点击菜单实现切换主界面组件
    子组件菜单组件 MenuComponent列表组件 ExtTelListComponent状态组件 ExtTelStatusComponent父组件界面主体MainIndex 实现功能:在 MainIndex中引入三个子组件 通过点击 菜单组件切换加载 列表组件和状态组件 实现效果一、菜单组件 MenuComponent<......
  • Vue3+.net6.0 六 条件渲染
    v-if,v-else-if,v-else控制元素是否渲染,不满足条件的时候不会有相应元素。<divv-if="type==='A'">A</div><divv-else-if="type==='B'">B</div><divv-else-if="type==='C'">C&l......