微信小程序上传资源到oss的两种方式
oss在小程序上传资源的方法和实践远没有在浏览器的全面,官方只有一个直传的介绍。其实在小程序端要写的代码很少也很简单,主要是前置的准备操作。下面主要介绍上传的前置操作和上传的两种方法。
前置操作
官网地址文档:微信小程序直传实践
大致步骤
- 在阿里云oss创建RAM角色之后,在服务端根据配置生成签名(服务端生成,客户端生成。推荐用服务端生成STS签名)
- 配置微信小程序,使用Bucket域名配置微信小程序的合法域名,具体可在官方文档中可见。
- 根据业务书写相关小程序代码,并进行上传。
以上传头像并保存为例
- 如下图
方式一
服务端生成签名,客户端使用接口调用,进行上传。 (官网有各个服务端的实例代码,可供参考)
小程序代码(uniapp代码)
<template>
<view class="index-page container">
<view class="avatarbox">
<button
class="avatarbox-btn"
open-type="chooseAvatar"
@chooseavatar="onChooseAvatar"
></button>
<image class="avatarbox-img" :src="avatarUrl"></image>
</view>
<view class="name flex">
<view class="name-label">昵称</view>
<view class="name-value">
<input
type="nickname"
class="nickname-input"
placeholder="请输入昵称"
placeholder-style="color: rgba(22, 24, 35, 0.34);font-weight: 400;line-height: 44rpx;"
@change="onInputChange"
v-model="nickname"
/>
</view>
</view>
<view class="oper-btn flex-xy-center" @click="goNext">下一步</view>
</view>
</template>
<script>
import {
generateuuid } from "@/utils/util";
import {
getUrlExtension } from "@/utils/common";
import dayjs from "dayjs";
export default {
data() {
return {
avatarUrl:
"https://dtmtask-o.doutuimao.net/dtmsite/dtmbuiltin/wxvideo/window/avatar.png",
nickname: "",
ossConfig: {
},
queryInfo: {
},
};
},
async onLoad(options) {
this.queryInfo = options;
console.log(options,'options')
},
methods: {
// 选择头像
async onChooseAvatar(e) {
console.log(e);
this.avatarUrl = e.detail.avatarUrl;
},
// 获取oss config,可根据具体前后端定义约定
async getOssConfig() {
const res