vue3 TS vite element ali-oss使用方式
安装ali-oss包
npm i ali-oss -S
写一个ali-oss.ts文件,封装函数 Client
const OSS = require('ali-oss') // import Oss from 'ali-oss' /** * [accessKeyId] {String}:通过阿里云控制台创建的AccessKey。 * [accessKeySecret] {String}:通过阿里云控制台创建的AccessSecret。 * [bucket] {String}:通过控制台或PutBucket创建的bucket。 * [region] {String}:bucket所在的区域, 默认oss-cn-hangzhou。 */ //Client.ts interface OSSData { region?: String //oss-cn-beijing-internal.aliyuncs.com accessKeyId?: String accessKeySecret?: String securityToken?: String bucket?: String } export default function Client(data:OSSData) { //后端提供数据 return new OSS({ region: 'oss-cn-beijing', //oss-cn-beijing-internal.aliyuncs.com accessKeyId: data.accessKeyId, accessKeySecret: data.accessKeySecret, stsToken: data.securityToken, bucket: data.bucket }) }
<div style='color:red;font-size:20px;'>这里注意<div>
vite 默认不支持commonjs语法,所以使用require会报错。解决方案
安装vite-plugin-require-transform
npm i vite-plugin-require-transform --save-dev
配置vite.config.js
plugins: [ requireTransform({ fileRegex: /.ts$|.tsx$|.vue$|.js$/ }) ]
<div style='color:red;font-size:20px;'>再次注意<div>
因为阿里OSS文档的后台示例
package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" "os" ) func main() { // 从STS服务获取的安全令牌(SecurityToken)。 securitytoken := "yourSecurityToken" //上面获取的临时授权的数据里的Credentials.SecurityToken // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。 // 从STS服务获取临时访问凭证后,您可以通过临时访问密钥和安全令牌生成OSSClient。 // 创建OSSClient实例。 // 第一个参数就是bucket的Endpoint,可以在对象储存oss控制台的bucket的概览得到,例如http://oss-cn-beijing.aliyuncs.com // 第二个参数就是上面获取的临时授权的数据里的Credentials.AccessKeyId // 第三个参数就是上面获取的临时授权的数据里的Credentials.AccessKeySecret client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken(securitytoken)) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // 填写Bucket名称,例如examplebucket。 bucketName := "examplebucket" // 填写Object的完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 objectName := "exampledir/exampleobject.txt" // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 filepath := "D:\\localpath\\examplefile.txt" bucket,err := client.Bucket(bucketName) // 通过STS授权第三方上传文件。 err = bucket.PutObjectFromFile(objectName,filepath) fmt.Println(err) }
所以后台返回token的名字是securitytoken,而ali-OSS的示例名叫stsToken,记住自己对应上,安装我的示例写
element-plus代码
<template> <el-upload accept="" v-model:file-list="fileList" :http-request="handleUpload" :before-upload="beforeUpload" action="" list-type="picture-card" :auto-upload="true" > <slot name="default" class="el-icon-plus" /> </el-upload> </<template> <script lang="ts" setup> //Client.js 这里引入刚才封装好的Client函数 import Client from './ali-oss.js' import { ref } from 'vue' import type { UploadUserFile } from 'element-plus' const fileList = ref<UploadUserFile[]>([]) const handleUpload = async (option: Object) => { console.log(option) } // 这里是接口,会返回 import { OssAuthorize } from '@/utils/publicData' function beforeUpload(file: any) { console.log(file) OssAuthorize().then((response) => { // response.data.accessKeyId = response.data.accessKeyId.replace('STS.', '') const client = Client(response.data) client.multipartUpload(file.name, file).then((res: any) => { console.log(res) }) }) } </script>
上传成功后会返回的数据里requestUrls
这个是个数组 里面放的是图片链接
最后关于oss的方法使用
补充上传文件类型、大小、图片像素判断,请写file.js并引入使用的地方
//图片类型验证 export function verificationFileType(file, fileTypes) { const filePath = file.name //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false let isNext = false const fileEnd = filePath.substring(filePath.indexOf('.')) for (let i = 0; i < fileTypes.length; i++) { if (fileTypes[i] == fileEnd) { isNext = true break } } if (!isNext) { file.value = '' return false } return true } //图片大小验证 export function verificationFileSize(file, maxSize) { const fileSize = file.size const size = fileSize / 1024 if (size > maxSize) { return false } else if (size <= 0) { return false } return true } //图片尺寸验证 export function verificationFilePixel(file, ratio = 1.5, cb) { //读取图片数据 const filePic = file const reader = new FileReader() reader.onload = function (e) { const data = e.target.result //加载图片获取图片真实宽度和高度 const image = new Image() image.src = data const width = image.width console.log(width) const height = image.height if (width / height === ratio) { cb && cb(true) } else { cb && cb(false) return false } } reader.readAsDataURL(filePic) }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。