微信小程序里如何用阿里云上传视频图片

为了微信小程序客服端实现自拍视频能够分享给多个好友,我们需要把小程序自拍的视频存储到服务器,而阿里云在性能和速度上比较不错,所以我们选择了阿里云作服务器。

阿里云官方文档:

https://help.aliyun.com/document_detail/31925.html?spm=a2c4g.11186623.6.634.AMs4Fj

需要由后台提供接口,前端获取一些必要参数

纯手写,踩了半天多的坑干出来了。。。

网上也有对于阿里云如何在微信小程序里使用,但是很不全,包括阿里云文档的最佳实践里。

上传流程:

选择图片-->获取到图片临时路径,将图片临时路径存入data

点击发布按钮-->获取oss参数

获取oss参数成功-->执行上传阿里云

上传阿里云成功-->执行上传服务器

上传服务器成功-->结束整个上传流程

由于为了方便大家浏览,没有用函数回调. 

大家可以根据自己的需求,结合自己的场景,来进行函数回调或者使用ES6的Promise方法.

上传阿里云过程中几个容易忽视的坑: 图片路径处理/时间戳判断

话不多说上代码了。

 1   upvideo(){
 2          var aliOssParams =  util.aliOssParams();//主要是获取上传阿里云的加密策略policy和签名signature;以及上传自己要上传到阿里云的地址,当然还有自己阿里云accessid。
 3           //上传视频到阿里云
 4           var that = this;
 5           wx.chooseVideo({
 6              maxDuration: 10,
 7              success: function (res) {
 8                var tempFilePath = res.tempFilePath;
 9                var stringFilePath = String(tempFilePath);
10                var indexType = stringFilePath.lastIndexOf('.');
11                var type = stringFilePath.substring(indexType);
12                var alikey = 'video/'+new Date().getTime() + 
13                 Math.floor(Math.random() * 1000)+ type ;//随机1000内的数加上时间戳作为你存放在阿里云video目录下名字和类型。
14                wx.uploadFile({
15                  url:aliOssParams.host,
16                  filePath: tempFilePath,
17                  name: 'file',
18                  formData: {
19                    name: tempFilePath,
20                    key: alikey,//这个是关键它是定义存放在阿里云那个目录下
21                    policy:aliOssParams.policy,//上传阿里云的加密策略
22                    OSSAccessKeyId: aliOssParams.aid,//自己阿里云的aid
23                    success_action_status: "200",
24                    signature: aliOssParams.signature,//上传阿里云的签名
25                  },
26                  success: function (res) {
27                   var videoUrl = aliOssParams.host+'/'+alikey;//这就是
28              刚上传阿里云后的存放的地址链接,通过它打开你刚上传视频。
29                   that.videoUrl = videoUrl;
30                    console.log('that',that,videoUrl);
31                    wx.showToast({
32                      title: "上传成功",
33                      icon: 'success',
34                      duration: 1000
35                    })
36                  },
37                  fail: function ({ errMsg }) {
38                    wx.showToast({
39                      title: "上传失败",
40                      duration: 1000
41                    })
42                  },
43                })
44              }
45            })
46         

  通过代码大家可以看到最关键的是啥,如何获取加密策略和签名了,当然了,阿里云最佳实践里有demo,但是crypto这个库已经废弃了,它demo给你带过来的crypto,你只能自己去提取了。

 这里是我提为大家提取的crypto函数,直接copy用。

+ View Code

  有了上面的crypto工具函数了,就去看看具体如何生成签名与加密策略吧。。

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import base64 from "base-64"

import {Crypto} from "./crypto.js"

const util = {

    aliOssParams(){

        var aid = "xxxxxxx";//你自己的阿里云的accessid

        var aky="xxxxxxxxxx";//你自己的阿里云的accesskey

        var host = "https://xxxxxxxxx.aliyuncs.com";//你自己的阿里云域名

        var policyText = {

                "expiration""2022-01-01T12:00:00.000Z",//上传的文件失效日期自己定义

                "conditions": [

                ["content-length-range", 0, 10485760000]//上传的内容大小,自己定义

                ]

        };

        var policy = base64.encode(JSON.stringify(policyText));//生成的加密策略

        var bytes = Crypto.util.HMAC(Crypto.util.SHA1, policy, aky, { asBytes: true }) ;

        var signature = Crypto.util.bytesToBase64(bytes);//生成的签名

        return {

                        policy: policy,

                       signature:signature,

                      aid:aid,

                      host: host

                   }

    }

 

}

 

export {util}                                                                               

  

 至于如何上传图片,大体如下,请保证以上都已经跑通了,base64记得你上面引到。。

多张图片的上传如此

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

upMyImg(){

  var aliOssParams =  util.aliOssParams();

  var that = this;

  wx.chooseImage({

     count: 9,  //最多可以选择的图片总数

     // sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有

     sourceType: ['album''camera'], // 可以指定来源是相册还是相机,默认二者都有

     success: function (res) {

       // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片

       var tempFilePaths = res.tempFilePaths;

       //启动上传等待中...

       wx.showToast({

         title: '正在上传...',

         icon: 'loading',

         mask: true,

         duration: 10000

       })

       var uploadImgCount = 0;

 

       var tempFilePath;

       var stringFilePath = '';

       var alikey = '' ;

       var type='';

 

       for (var i = 0, h = tempFilePaths.length; i < h; i++) {

            // stringFilePath= String(tempFilePaths[i]);

            // type = stringFilePath.substring(stringFilePath.lastIndexOf('.'));

            alikey = 'imagees/'+new Date().getTime() + Math.floor(Math.random() * 150)+ '.jpg';

            that.srcs.push(tempFilePaths[i]);

            that.setData({srcs: that.srcs});

         wx.uploadFile({

           url: aliOssParams.host,

           filePath: tempFilePaths[i],//上传图片的路径

           name: 'file',

           formData: {

             key: alikey,

             name: tempFilePaths[i],

             policy:aliOssParams.policy,

             OSSAccessKeyId: aliOssParams.aid,

             success_action_status: "200",

             signature: aliOssParams.signature,

           },

           success: function (res) {

             uploadImgCount++;

             console.log('rrrs',res,tempFilePaths[i]);

             // var data = JSON.parse(res.data);

             //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }

             // console.log('rrr',data);

             console.log('ddd222',res,aliOssParams.host,alikey);

             // var productInfo = that.data.productInfo;

             // if (productInfo.bannerInfo == null) {

             //   productInfo.bannerInfo = [];

             // }

             // productInfo.bannerInfo.push({

             //   "catalog": data.Catalog,

             //   "fileName": data.FileName,

             //   "url": data.Url

             // });

             // that.setData({

             //   productInfo: productInfo

             // });

 

             //如果是最后一张,则隐藏等待中

             if (uploadImgCount == tempFilePaths.length) {

                 // that.srcs.push(tempFilePaths[i]);

                 console.log(that.srcs,3222);

               wx.hideToast();

               wx.showToast({

                 title: "上传成功",

                 icon: 'success',

                 duration: 1000

               })

             }

           },

           fail: function (res) {

             wx.hideToast();

             wx.showModal({

               title: '错误提示',

               content: '上传图片失败',

               showCancel: false,

               success: function (res) { }

             })

           }

         });

       }

     }

   })

 

 

// 上传图片完

}

  

都是自己亲测,亲坑。。。码字很累。解决了你的问题,就分享一哈吧。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值