通过阅读本文,您可以了解微信小程序上传的方式和基本流程。

前提条件

在页面上引入下面的Javascript脚本,更多信息,请参见小程序上传SDK
import VODUpload from 'aliyun-upload-sdk-1.0.0.min.js'

操作步骤

  1. 请求上传地址和凭证或STS。
    • 请求上传地址和凭证

      上传图片和上传视频获取上传地址和凭证所请求的API不同,如下所示:

      • 上传视频:客户端向AppServer发送请求,AppServer通过OpenAPI向阿里云点播服务发送CreateUploadVideo请求。请求成功将返回上传地址、上传凭证以及VideoId,AppServer将结果返回给客户端。
      • 上传图片:客户端向AppServer发送请求,AppServer通过OpenAPI向阿里云点播服务发送CreateUploadImage请求。请求成功将返回上传地址、上传凭证以及ImageURL,AppServer将结果返回给客户端。
    • 请求STS

      通过STS方式,客户端向AppServer发送请求,AppServer向阿里云STS服务请求临时STS凭证。请求成功将返回STS凭证,AppServer将结果返回给客户端。

      request_sts
  2. 初始化上传实例。
    1. 声明VODUpload初始化回调。
      var uploader = new VODUpload({
             //阿里账号ID,必须有值
             userId:"0",
             //上传到点播的地域,默认值为'cn-shanghai',//eu-central-1,ap-southeast-1
             region:"",
             //网络原因失败时,重新上传次数,默认为3
             retryCount: 3,
             //网络原因失败时,重新上传间隔时间,默认为2秒
             retryDuration: 2,
            //开始上传
            'onUploadstarted': function (uploadInfo) {
            },
            //文件上传成功
            'onUploadSucceed': function (uploadInfo) {
            },
            //文件上传失败
            'onUploadFailed': function (uploadInfo, code, message) {
            },
            //文件上传进度,单位:字节
            'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
            },
            //上传凭证超时
            'onUploadTokenExpired': function (uploadInfo) {
            },
            //全部文件上传结束
            'onUploadEnd':function(uploadInfo){
             }
        });
    2. 初始化上传实例有两种方式,如下所示:
      • 上传地址和凭证方式
        说明 推荐使用上传地址和凭证方式进行初始化。

        请求获取的上传地址和凭证初始化时无需设置,在上传开始后触发的onUploadStarted回调中调用setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress,videoId);方法进行设置。

        当token超时,会触发onUploadTokenExpired回调,需要调用resumeUploadWithAuth(uploadAuth)方法,设置新的上传凭证继续上传。

        upload_address_auth
        var uploader = new VODUpload({
               //阿里账号ID,必须有值
               userId:"0",
               //网络原因失败时,重新上传次数,默认为3
               retryCount: 3,
               //网络原因失败时,重新上传间隔时间,默认为2秒
               retryDuration: 2,
              //开始上传
              'onUploadstarted': function (uploadInfo) {
                log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                //上传方式1,需要根据uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress,如果videoId有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口
                if (uploadInfo.videoId) {
                    //如果uploadInfo.videoId存在,调用刷新视频上传凭证接口
                 }
                 else{
                    //如果uploadInfo.videoId不存在,调用获取视频上传地址和凭证接口
                 }
                //从点播服务获取的uploadAuth、uploadAddress和videoId,设置SDK
                 uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
              },
              //文件上传成功
              'onUploadSucceed': function (uploadInfo) {
                log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
              },
              //文件上传失败
              'onUploadFailed': function (uploadInfo, code, message) {
                log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
              },
              //文件上传进度,单位:字节
              'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
                  log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
              },
              //上传凭证超时
              'onUploadTokenExpired': function (uploadInfo) {
                  console.log("onUploadTokenExpired");
                  //实现时,根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
                  //从点播服务刷新的uploadAuth,设置到SDK里
                  uploader.resumeUploadWithAuth(uploadAuth);
              },
              //全部文件上传结束
              'onUploadEnd':function(uploadInfo){
                   console.log("onUploadEnd: uploaded all the files");
               }
          });
      • STS方式

        请求获取的STS初始化时无需设置,而是在上传开始后触发的onUploadStarted回调中调用setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken);方法进行设置。

        当token超时,会触发onUploadTokenExpired回调,需要调用resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)方法,设置新的STS继续上传。

        var uploader = new VODUpload({
               //网络原因失败时,重新上传次数,默认为3
               retryCount: 3,
               //网络原因失败时,重新上传间隔时间,默认为2秒
               retryDuration: 2,
              //开始上传
              'onUploadstarted': function (uploadInfo) {
                log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
                //获取STS Token,设置到SDK
                 uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken);
              }
              //文件上传成功
              'onUploadSucceed': function (uploadInfo) {
                log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
              },
              //文件上传失败
              'onUploadFailed': function (uploadInfo, code, message) {
                log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
              },
              //文件上传进度,单位:字节
              'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
                  log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
              },
              //上传凭证超时
              'onUploadTokenExpired': function (uploadInfo) {
                  console.log("onUploadTokenExpired");
                  //重新获取STS token,恢复上传
                  uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken);
              },
              //全部文件上传结束
              'onUploadEnd':function(uploadInfo){
                   console.log("onUploadEnd: uploaded all the files");
               }
          });
  3. 列表管理。
    • 添加上传文件

      需要使用wx.chooseImage、wx.chooseVideo选择文件。获取到选择的文件后,添加到上传列表中。

          wx.chooseVideo({
              success: function (res) {
                  var file = {url: res.tempFilePath, coverUrl: res.thumbTempFilePath};
                  var userData = '{"Vod":{}}';
                  uploader.addFile(file, null, null, null, userData)
              }
          })

      上传时,可以选择是否启用水印和优先级,userData是一个JSON对象字符串。第一级的Vod必须设置,Vod下面添加属性,userData支持的属性请参见点播服务的接口createUploadVideo,接口示例如下:

       var userData = '{"Vod":{"Title":"test","CateId":"234"}"}';
    • 删除上传文件

      index对应listFiles接口返回列表中元素的索引。

       uploader.deleteFile(index);
    • 取消单个文件上传
       uploader.cancelFile(index);
    • 恢复单个文件上传
       uploader.resumeFile(index);
    • 获取上传文件列表
       uploader.listFiles();
    • 清理上传文件列表
       uploader.cleanList();
  4. 上传控制。
    • 开始上传
        uploader.startUpload();
    • 停止上传
       uploader.stopUpload();
    • 上传凭证失效后恢复上传
       uploader.resumeUploadWithAuth(uploadAuth);
    • 设置上传地址和上传凭证

      设置上传地址和上传凭证方法在onUploadstarted回调里调用,此回调的参数包含uploadInfo的值。

       uploader.setUploadAuthAndAddress(uploadInfo,uploadAuth, uploadAddress, videoId);
    • 设置STS Token

      设置STS Token方法在onUploadstarted回调里调用,此回调的参数包含uploadInfo的值。

      uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret,secretToken);
    • 上传STS Token失效后恢复上传
      uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);