更新记录
1.0.1(2024-02-04) 下载此版本
插件重新上传
1.0.0(2024-01-09) 下载此版本
初始化插件
平台兼容性
uni-app
Vue2 | Vue3 | Chrome | Safari | app-vue | app-nvue | Android | iOS | 鸿蒙 |
---|---|---|---|---|---|---|---|---|
√ | √ | √ | √ | √ | - | - | - | - |
微信小程序 | 支付宝小程序 | 抖音小程序 | 百度小程序 | 快手小程序 | 京东小程序 | 鸿蒙元服务 | QQ小程序 | 飞书小程序 | 快应用-华为 | 快应用-联盟 |
---|---|---|---|---|---|---|---|---|---|---|
√ | √ | √ | √ | √ | √ | - | √ | √ | √ | √ |
其他
多语言 | 暗黑模式 | 宽屏模式 |
---|---|---|
× | × | √ |
一、安装OSS
在项目的根目录下执行命令:
npm install ali-oss --save
二、获取oss访问域名
登录阿里云oss控台,在概览里面获取bucket域名,
Bucket 域名示例:test.oss-cn-beijing.aliyuncs.com
const client = new OSS({
endpoint: "oss-cn-beijing.aliyuncs.com",
***: ***,
***: ***,
bucket: "test",
});
三、获取OSS秘钥
登录阿里云个人中心,获取账户的AccessKey ID和AccessKey Secret,推荐使用子用户的AccessKey
四、设置CORS支持跨域
在bucket里面:数据安全 -> 跨域设置,按下图创建一条规则,勾选:GET、POST、PUT、DELETE、HEAD
五、修改配置文件
将ossutil文件夹放在js_sdk文件夹下,打开文件/js_sdk/ossutil/uploadFile.js,将前面获取到的信息复制到此处
const endpoint = "xxxxxxx"; // 示例:'oss-cn-hangzhou',填写Bucket所在地域。
const *** = "xxxxxxxxx"; //*** 去你的阿里云上控制台上找
const *** = "xxxxxxxxx"; //*** 去你的阿里云上控制台上找
const bucket = "xxxxxxxxx"; // 示例:'my-bucket-name',填写存储空间名称。
六、页面调用
页面引入方式为:
<template>
<uni-file-picker :auto-upload="false" class="imgItem" :readonly="type == 'view'? true: false"
v-model="compressStart" fileMediatype="image" file-extname="png,jpg" mode="grid" :limit="1"
@select="selectImg($event)" @delete="delImg($event)">
</uni-file-picker>
</template>
<script>
import {
uploadFile,
deleteFile
} from "../../js_sdk/ossutil/uploadFile.js";
/**
* @description 上传至阿里云
*/
async selectImg(e) {
let filearr = e.tempFiles
// 支持多图片上传
for (var i = 0; i < filearr.length; i++) {
let filepath = filearr[i].path;
try {
let result = await uploadFile(filepath, filearr[i].extname, '/');
if (this.fileMap == null) {
this.fileMap = new Map();
}
this.fileMap.set(filepath, result);
} catch (e) {
uni.showToast({
title: '文件上传OSS失败',
icon: 'none'
})
}
}
},
/**
* @description 文件删除
*/
async delImg(e) {
if (this.fileMap == null) {
return;
}
try {
let fileUrl = this.fileMap.get(e.tempFilePath);
await deleteFile(fileUrl);
this.fileMap.delete(e.tempFilePath);
} catch (e) {
uni.showToast({
title: '文件删除失败',
icon: 'none'
})
}
},
</script>
uploadFile函数对应的3个参数依次是:
- filepath: 本地的文件路径,代码不用修改
- extname: 文件扩展名,示例文件名:123.png 扩展名为png,代码不用修改
- dir: 文件上传到oss的哪个文件夹,为空则上传到根目录,示例:/test/a/
delImg 函数不用修改直接使用
七、技术交流,有问题可在内反馈
QQ:705623891 <img border="0" src="//pub.idqqimg.com/wpa/images/group.png" alt="软件交流" title="软件交流***">
八、提醒
前端签名有密钥泄露风险,注意妥善保管和 有问题请***
九、打赏
若帮助到您,请随意打赏