当前位置:   article > 正文

阿里云JavaScript上传视频_js 阿里云上传视频

js 阿里云上传视频

使用的是JavaScript的方法去上传视频: 选导入必要的js

https://help.aliyun.com/document_detail/51992.html?spm=a2c4g.11186623.2.41.71cd6bd1zmC1Gk#h2-web-sdk-3 我用的是1.5版本的

上jq代码:

` //视频上传到阿里云
    var uploader = new AliyunUpload.Vod({
                    //阿里账号ID,必须有值 ,值的来源https://help.aliyun.com/knowledge_detail/37196.html
                    //userId:"122",  **//这个当时我没写  也可以上传 我也不知道为什么  大佬可以说一下**
                    //分片大小默认1M,不能小于100K
                    partSize: 1048576,
                    //并行上传分片个数,默认5
                    parallel: 5,
                    //网络原因失败时,重新上传次数,默认为3
                    retryCount: 3,
                    //网络原因失败时,重新上传间隔时间,默认为2秒
                    retryDuration: 2,
                    // 开始上传
                    'onUploadstarted': function(uploadInfo) {
                        console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" +
                            uploadInfo.bucket + ", object:" + uploadInfo.object);
                        //上传方式1, 需要根据uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress,如果videoId有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口
                        //uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
                              ~~var fileName=$("#file").val();
                              //判断上传类型
                              var fileType = fileName.substr(
                                      fileName.lastIndexOf(".")).toUpperCase();
                              if (fileType != ".MP4") {
                                  popup.alert.show("提示", "视频类型错误(请选择MP4格式)",
                                          function() {
                                           $("#file").val("");  
                                              location.reload();
                                          });
                                  popup.loading.hide();
                                  return false;
                              }~~ 
                             **//调用此ajax 去拿到uploadAddress、uploadAuth、videoId 后端代码在后面  我传的参数是文件名与文件大小** 
                           $.ajax({
                                  url: "${ctx}/course/video/videoUpload",
                                  data:{fileName:fileName,fileSize:$("#file")[0].files[0].size},
                                  dataType: 'json',
                                  type: 'post',
                                  success: function(json) {
                                      var uploadAddress = json.uploadAddress;
                                      var uploadAuth = json.uploadAuth;
                                      var videoId = json.videoId;
                                      //得到视频上传的凭证
                                      vId = videoId;
                                      //如果此部分执行说明后端返回凭证成功,从data中获取返回的uploadAddress、uploadAuth、videoId,然后调用阿里云的api直接进行文件上传  **必需要将这三个参数传进去否则无法上传,否则当用VideoId去获取视频地址时会报 此视频上传中或什么什么的 忘了哈哈**
                                      uploader.setUploadAuthAndAddress(uploadInfo, json.uploadAuth, json.uploadAddress, json.videoId);
                                  }
                        });
                    },
                    // 文件上传成功
                    'onUploadSucceed': function(uploadInfo) {
                        console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" +
                            uploadInfo.bucket + ", object:" + uploadInfo.object + uploadInfo);
                        //文件上传成功后执行所需逻辑
                    },
                    // 文件上传失败
                    'onUploadFailed': function(uploadInfo, code, message) {
                        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
                        popup.alert.show("提示",message+"--code:"+code, function() {
                        });
                    },
                    // 文件上传进度,单位:字节
                    'onUploadProgress': function(uploadInfo, totalSize, loadedPercent) {
                        console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(
                            loadedPercent * 100) + "%");
                        //控制台显示进度
                        popup.loading.show();
                    },
                    // 上传凭证超时
                    'onUploadTokenExpired': function(uploadInfo) {
                        console.console.log("onUploadTokenExpired");
                        popup.alert.show("提示","上传凭证超时", function() {});
                        //上传方式1  实现时,根据uploadInfo.videoId调用刷新视频上传凭证接口重新获取UploadAuth
                        // uploader.resumeUploadWithAuth(uploadAuth);
                        // 上传方式2 实现时,从新获取STS临时账号用于恢复上传
                        // uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
                    },
                    //全部文件上传结束
                    'onUploadEnd': function(uploadInfo) {
                        console.log("onUploadEnd: uploaded all the files");
                        popup.loading.hide();
                        popup.alert.show("提示","上传成功", function() {});
                        //将返回的videoId填充到隐藏框中
                        $("#videoId").val(vId);
                    }
                });
        
                var userData = {
                    Vod: {
                        UserData: {
                            IsShowWaterMark: false,
                            Priority: 7
                        }
                    }
                };
                **//这是循环获取你的文件并传进 uploader 中   html:<input type="file" name="file" id="file" class="required"/>**
                document.getElementById("file").addEventListener('change', function(event) {
                        for (var i = 0; i < event.target.files.length; i++) {
                            // 逻辑代码
                            uploader.addFile(event.target.files[i], null, null, null, JSON.stringify(userData));
                        }
                        **//将文件传入到你的uploader 后 就要调用 此方法来开始上传 这时候就会走上面第一个function 'onUploadstarted': function(uploadInfo)** 
                        uploader.startUpload();
                    });`
  • 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
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103

后端代码 AccessKeyId 与AccessKeySecret 是必需的

我写了一个工具类

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;

public class AliyunVideoUtils {

	 private static final Logger logger = LoggerFactory.getLogger(AliyunVideoUtils.class);
	 private static String accessKeyId = null;
	 private static String accessKeySecret = null;
	 private static DefaultAcsClient client = null;
	 **//我用的时xml 方式去记录我 AccessKeyId 与AccessKeySecret 的 使用静态块的形式去加载出来**
static {
  try {
   InputStream is = AliyunVideoUtils.class.getResourceAsStream("/alivod.properties");
   if (is == null) {
    throw new RuntimeException("系统找不到阿里云video相关配置文件");
   }
   Properties properties = new Properties();
   properties.load(is);
   accessKeyId =properties.getProperty("AccessKeyId");
   accessKeySecret =properties.getProperty("AccessKeySecret");
  } catch (IOException e) {
   e.printStackTrace();
  }
  client = new DefaultAcsClient(
    DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret));
 }
**//此方法就是去获取uploadAddress、uploadAuth、videoId 这三个参数的 上面的ajax 就是调用 此方法**
public static CreateUploadVideoResponse createUploadVideo(String fileName, long fileSize) {
  CreateUploadVideoResponse response = null;
  try {
   CreateUploadVideoRequest request = new CreateUploadVideoRequest();
   request.setFileName(fileName); //传入文件名
   request.setFileSize(Long.valueOf(fileSize)); //文件大小
   request.setTitle(fileName); //文件标题
   response = client.getAcsResponse(request); //记住我的AccessKeyId 与AccessKeySecret 是在静态中已经传入到new DefaultAcsClient(
    //DefaultProfile.getProfile("cn-shanghai"//这是区域, accessKeyId, accessKeySecret));调用DefaultProfile.getProfile 获取DefaultAcsClient 实例
  } catch (ServerException e) {
   logger.error("CreateUploadVideoRequest Server Exception:{}", e.getMessage(), e);
  } catch (ClientException e) {
   logger.error("CreateUploadVideoRequest Client Exception:{}", e.getMessage(), e);
  }
  return response;
 }
 
 /**
  *  如上传地址与上传凭证失效了  就调用此方法 根据传入videoId 重新获取上传地址与上传凭证uploadauth与uploadAddress
  * @param videoId
  * @return
  */
 public static RefreshUploadVideoResponse refreshUploadVideo(String videoId) {
  RefreshUploadVideoResponse response = null;
  try {
   RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
   request.setVideoId(videoId);
   response = client.getAcsResponse(request);
  } catch (ServerException e) {
   logger.error("RefreshUploadVideoRequest Server Exception:{}", e.getMessage(), e);
   e.printStackTrace();
  } catch (ClientException e) {
   logger.error("RefreshUploadVideoRequest Client Exception:{}", e.getMessage(), e);
  }
  return response;
 }
 
/**
      * 获取视频的播放地址
  */
 public static GetPlayInfoResponse getPlayInfo(String uuid) {
  // 创建SubmitMediaInfoJob实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-Shanghai",                // // 点播服务所在的地域ID,中国大陆地域请填cn-shanghai
                accessKeyId,        // 您的AccessKey ID
                accessKeySecret);    // 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        //获取视频基本信息
//        GetVideoPlayAuthRequest requestAuth = new GetVideoPlayAuthRequest();
//        request.setVideoId(uuid);
//        GetVideoPlayAuthResponse videoPlayAuthReq = null;
        // 视频ID。
        request.setVideoId(uuid); //这是VideoId你上传完成后返回给你的VideoId 要通过这个id去获取视频播放地址
        request.setFormats("mp4"); // 这是指定获取什么类型视频地址  但是你上传的视频 一定是这个格式 不指定会有一两个视频格式视频 一个是你原
        //上传的格式,一个是m3u8格式
        try {
            GetPlayInfoResponse response = client.getAcsResponse(request);
           // 此是获取视频第一帧 System.out.println(response.getVideoBase().getCoverURL());
            return response;
//            System.out.println(new Gson().toJson(response));
//            for (GetPlayInfoResponse.PlayInfo playInfo : response.getPlayInfoList()) {
//                // 播放地址
//                 System.out.println("PlayInfo.PlayURL = " + playInfo.getPlayURL());
//            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
 }
 //response.getVideoBase() 这个里面是视频信息
 //response.getPlayInfoList() 播放地址的在里面
  • 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
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117

要注意获取来的信息只在3000秒内有效 要导入的包上面有

我是看这位大哥写的来实现的如看不懂小弟的 可点击这转去大哥写的文章:https://blog.csdn.net/chihang6/article/details/83241142

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/246042
推荐阅读
相关标签
  

闽ICP备14008679号