uni-app
微信小程序直传图片、视频到 oss
微信小程序上传文件到阿里云oss的代码:
https://www.jianshu.com/p/34d6dcbdc2e5
、https://www.cnblogs.com/ziyoublog/p/13085217.html
微信小程序直传实战:https://help.aliyun.com/document_detail/92883.html?spm=a2c4g.11186623.6.670.5265350asB84kG
oss官方API 错误中心:https://error-center.aliyun.com/status/product/Oss
一、配置 Bucket
跨越访问
- 登录 OSS 管理控制台
- 单机 Bucket 列表,之后单击目标 Bucket 名称
- 单击权限管理 > 跨域设置,在跨域设置区域单击设置
- 单击创建规则,配置如下图所示
二、微信公众号后台域名配置
三、配置密钥,上传
-
在
config.js
文件中配置OSSAccessKeyId
、AccessKeySecret
和fileHost
-
uploadFile.js
const env = require('./env.js'); const Base64 = require('./Base64.js'); require('./crypto/hmac.js'); require('./crypto/sha1.js'); const Crypto = require('./crypto/crypto.js'); const uploadFile = function (filePath, filew, objectId, successCB, errorCB) { if (!filePath || filePath.length < 9) { uni.showModal({ title: '视频错误', content: '请重试', showCancel: false }) return; } console.log('上传视频...'); const aliyunFileKey = fileW + '' + (new Date().getTime()) + '_' + objectId + '.mp4'; const aliyunServerURL = env.aliyunServerURL; const accessid = env.accessid; const policyBase64 = getPolicyBase64(); const signature = getSignature(policyBase64); console.log('aliyunFileKey=', aliyunFileKey); uni.uploadFile({ url: aliyunServerURL, filePath: filePath, name: 'file', formData: { 'key': aliyunFileKey, 'OSSAccessKeyId': accessid, 'policy': policyBase64, 'Signature': signature, 'success_action_status': 200 }, success: function(res) { if (res.statusCode != 200) { errorCB(new Error('上传错误:' + JSON.stringify(res))); return; } console.log('上传视频成功', res); successCB(aliyunFileKey); }, fail: function(err) { err.wxaddinfo = aliyunServerURL; errorCB(err); } }) } const getPolicyBase64 = function() { let date = new Date(); date.setHours(date.getHours() + env.timeout); let srcT = date.toISOString(); const policyText = { "expiration": srcT, "conditions": [ ['content-length-range', 0, 20 * 1024 * 1024] ] } const policyBase64 = Base64.encode(JSON.stringify(policyText)); return policyBase64; } const getSignature = function(policyBase64) { const accesskey = env.accesskey; const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, { asBytes: true }); const signature = Crypto.util.bytesToBase64(bytes); return signature } modele.exports = uploadFile;
-
页面引入
import uploadImage from '@/components/ossutil/uploadFile.js'
-
完整功能页面
html代码块
<template> <view style="padding-bottom: 10rpx;"> <view class="cu-bar bg-white margin-top"> <view class="action">图片上传</view> <view class="action">{{imgList.length}}</view> </view> <view class="cu-form-group"> <view class="grid col-3 grid-square flex-sub"> <view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]"> <image :src="imgList[index]" mode="aspectFill"></image> <!-- @top.stop 组织点击事件继续传播 --> <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index"> <text class="cuIcon-close"></text> </view> </view> <view class="solids" @tap="ChooseImage" v-if="imgList.length < 6"> <text class="cuIcon-cameraadd"></text> </view> </view> </view> </view> </template>
vue代码块
<script> import uploadImage from '@/components/ossutil/uploadFile.js'; import main from '@/main.js' export default { data() { return { imgList: [], submit_img: [], oss_result: [] } }, onload:function(e) { }, methods: { // 图片上传 ChooseImage() { uni.chooseImage({ count: 9, // 默认9 sizeType: ['compressed'], // compressed 压缩图,original success: (res) => { if (this.imgList.length != 0) { this.imgList = this.imgList.concat(res.tempFilePaths); this.submit_img.push(res.tempFilePaths); } else { this.imgList = res.tempFilePaths this.submit_img.push(res.tempFilePaths); } for (var i = 0; i < this.imgList.length; i++) { // 显示消息提示框 // 上传图片 // 图片路径可自行修改 uploadImage(this.imgList[i], 'sd/suggest_img/jy', result => { console.log("返回的图片路径++++" + result); this.oss_result.push(result); }, fail => { console.log("fail++++" + JSON.stringify(fail)); }) } } }); }, // 预览图片 ViewImage(e) { uni.previewImage({ urls: this.imgList, current: e.currentTarget.dataset.url }); }, // 删除图片 DelImg(e) { uni.showModal({ content: '确定要删除吗?', cancelText: '取消', confirmText: '确定', success: res => { if (res.confirm) { this.imgList.solice(e.currentTarget.dataset.index, 1) this.submit_img.splice(e.currenTarget.dataset.index, 1) console.log("shengyu++++" + JSON.stringify(this.imgList)) } } }) } } } </script>