uni-app 微信小程序直传图片、视频到 oss

uni-app 微信小程序直传图片、视频到 oss

微信小程序上传文件到阿里云oss的代码: https://www.jianshu.com/p/34d6dcbdc2e5https://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 跨越访问

  1. 登录 OSS 管理控制台
  2. 单机 Bucket 列表,之后单击目标 Bucket 名称
  3. 单击权限管理 > 跨域设置,在跨域设置区域单击设置
  4. 单击创建规则,配置如下图所示
    在这里插入图片描述

二、微信公众号后台域名配置

在这里插入图片描述

三、配置密钥,上传

  1. config.js 文件中配置 OSSAccessKeyIdAccessKeySecretfileHost
    在这里插入图片描述

  2. 相关文件的下载

  3. 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;
    
  4. 页面引入

    import uploadImage from '@/components/ossutil/uploadFile.js'
    
  5. 完整功能页面

    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>
    
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值