edit-icon download-icon

Upload videos

Last Updated: Apr 19, 2018

Background

The following describes how to quickly build an audio and video file upload service based on the OSS service and MPS’s SDK upload.

Advantages

Uploading audio and video files using MPS’s SDK offers the following advantages:

  • Adds file list management.

  • Adds STS Token timeout update function.

  • Auto-retry function when network jitter occurs in the process of uploading.

  • File resume breakpoint function.

  • Workflow that automatically triggers the MPS service.

  • Configures media titles, tags, descriptions, categories, cover URLs, and more.

    Note:

    • Restrictions on resuming HTTP: does not allow cross-lifecycle. JS side page can not be refreshed, closed, and Android/iOS can not close the APP and mobile phone.

    • The same local file can only be uploaded once.

Upload service

Server creation

Consider mobile AK security issues, choose STS to upload files. To learn how using STS increases the security of the upload, see RAM and STS User Guide.

STS Activation Procedure

  1. Activate the OSS service, create a bucket, and log on to the OSS console.

  2. Find the basic configuration area on the OSS overview page and click the security token.

  3. Go to the Security Token Shortcut Configuration page.

  4. Authorize automatically and save parameters in the text boxes. Click Save AK Info to close the dialog and complete STS activation.

Build an application server

Configuration of app server sample code

This tutorial provides three development example programs available for download in three languages.

The download for each language pack contains a configuration file: config.json:

  1. {
  2. "AccessKeyID" : "",
  3. "AccessKeySecret" : "",
  4. "RoleArn" : "",
  5. "TokenExpireTime" : "900",
  6. "PolicyFile": "policy/all_policy.txt"
  7. }

Note:

  • AccessKeyID: Set the parameter value marked 1 in the above diagram.

  • AccessKeySecret: Set the parameter value marked 2 in the above diagram.

  • RoleArn: Set the parameter value marked 3 in the above diagram.

  • TokenExpireTime: Indicates the expiration time of the token obtained by the Android/iOS app. The minimum value is 900s. The default value can be retained.

  • PolicyFile : Fill in the list of rights to the Token file, the default value can not be modified.

This document has provided three token files defining the most common permissions in the policy directory. They are:

  • all_policy.txt: Specifies that the token has the authority to create or delete a bucket, to upload or download a file, and to delete a file under this account.

  • bucket_read_policy.txt: Specifies that the token has read access to the specified bucket under this account.

  • bucket_read_write_policy.txt: Specifies a token that grants read and write permissions for the specified bucket for this account.

If you want to create a token to grant read and write permissions for the specified bucket, replace $BUCKET_NAME in the bucket_read_policy.txt and bucket_read_write_policy.txt files with the name of the desired bucket.

Return format resolution:

  1. {
  2. "status":200,
  3. "AccessKeyId":"STS.3pYjsdgdgagdasdg",
  4. "AccessKeySecret":"rpnwO9kvEgetGdrddgsR2YrTtI",
  5. "Security":"CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVtbzI=",
  6. "Expiration":"2015-12-12T07:49:09Z",
  7. }

Note (the four variables shown below comprise a token) :

  • status indicates the result that the app retrieves the token. The app returns a 200 status code for successful retrieval of the token.

  • AccessKeyId indicates the AccessKeyId the Android/iOS app obtains when initializing the OSS client.

  • AccessKeySecret indicates the AccessKeySecret the Android/iOS app obtains when initializing the OSS client.

  • SecurityToken indicates the token the Android/iOS app initializes.

  • Expiration indicates the time when the token expires. The Android SDK will automatically determine the validity of the token and retrieve a new one as needed.

Examples of how to run code:

  • For JAVA (based on Java 1.7), after downloading and unzipping a pack,

    run this command: java -jar oss-token-server.jar (port). If you run java –jar oss-token-server.jar without specifying a port, the program listens to Port 7080. To change the listening port to 9000, run java –jar app-token-server.jar 9000. Specify the port number as needed.

  • For PHP, after you download and decompress the package, modify the config.json file and run php sts.php directly to generate a token. Then set up the app server at the specified address.

Use the MPS client SDK

Client Sample Code

This tutorial provides three development example programs available for download in three languages.

SDK core code

JS side

Before using the JS SDK, first open CORS Access to the OSS Bucket where you want to upload the video. Download JS Demo, open in a browser, the parameters on the page configuration are:

  • Configure the “HTTP Address” as the application server address configured above, for example, http://127.0.0.1:7080/.

  • Configure user Bucket.

  • Configure Bucket endpoint.

  • Click to select the file, select the file to be uploaded.

  • Click the Start Upload button.

  1. // Initialize the client
  2. var uploader = new VODUpload({
  3. // Start uploading
  4. 'onUploadstarted': function (uploadInfo) {;},
  5. // File uploaded successfully
  6. 'onUploadSucceed': function (uploadInfo) {console.log("Uploaded successfully");},
  7. // File upload failed
  8. 'onUploadFailed': function (uploadInfo, code, message) {console.log("Uploading failed");},
  9. // File upload progress, in bytes
  10. 'onUploadProgress': function (uploadInfo, totalSize, uploadedSize) {console.log("Upload progress");},
  11. // Security token timed out
  12. 'onUploadTokenExpired': function (uploadInfo) {console.log("Token timeout");}
  13. });
  14. // Get sts information
  15. result = httpGet(httpServer);
  16. stsToken = JSON.parse(result);
  17. uploader.init(stsToken.AccessKeyId, stsToken.AccessKeySecret, stsToken.SecurityToken, stsToken.Expiration);
  18. // File added successfully
  19. uploader.addFile(event.target.files[i], endpoint, bucket, object, userData);
  20. // Start uploading
  21. uploader.startUpload();

Android end

Make sure Android has added the following permissions:

  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
  3. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Download Android Demo, make the following changes:

  • Modify MainActivity inside serverUrl for the application server configuration address, such as http://192.168.0.2:7080/.

  • Configure user Bucket.

  • Configure the endpoint corresponding to the user Bucket.

  • Run Demo, click Add File.

  • Click Upload to check whether the file has been uploaded successfully under the uploadtest / directory of the OSS Bucket.

Main code:

  1. VODUploadClient uploader = new VODUploadClientImpl(getApplicationContext());
  2. VODUploadCallback callback = new VODUploadCallback() {
  3. @Override
  4. public void onUploadSucceed(UploadFileInfo info) {;}
  5. @Override
  6. public void onUploadFailed(UploadFileInfo info, String code, String message) {;}
  7. @Override
  8. public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {;}
  9. @Override
  10. public void onUploadTokenExpired(UploadFileInfo info) {
  11. // Get and update sts token.
  12. uploader.resumeWithToken("<accessKeyId>", "<accessKeySecret>", "<secretToken>", "<expireTime>");
  13. }
  14. @Override
  15. public void onUploadRetry(UploadFileInfo info, String code, String message) {;}
  16. @Override
  17. public void onUploadRetryResume(UploadFileInfo info) {;}
  18. @Override
  19. public boolean onUploadStarted(UploadFileInfo uploadFileInfo) {;}
  20. };
  21. // Get sts token and initialize
  22. uploader.init("<accessKeyId>", "<accessKeySecret>", "<secretToken>", "<expireTime>", callback);
  23. // File added successfully
  24. uploader.addFile("<uploadFilePath>", "<endpoint>", "<bucketName>", "<objectKey>");
  25. // Start uploading
  26. uploader.start();

iOS end

Download iOS Demo, make the following changes:

  • Modify the serverUrl in VODUploadDemo.m to configure the address for the application server, such as http://192.168.0.2:7080/.

  • Configure user Bucket.

  • Configure the endpoint corresponding to the user Bucket.

  • Run Demo, click Add File.

  • Click Upload to check whether the file has been uploaded successfully under the uploadtest / directory of the OSS Bucket.

Main code:

  1. // callback initialization
  2. OnUploadStartedListener testUploadStartedCallbackFunc = ^(UploadFileInfo* fileInfo) {;};
  3. OnUploadSucceedListener testSuccessCallbackFunc = ^(NSString* filePath){;};
  4. OnUploadFailedListener testFailedCallbackFunc = ^(NSString* filePath, NSString* code, NSString* message){;};
  5. OnUploadProgressListener testProgressCallbackFunc = ^(NSString* filePath, long uploadedSize, long totalSize) {;};
  6. OnUploadTokenExpiredListener testTokenExpiredCallbackFunc = ^{
  7. // Get and update sts token
  8. [uploader resumeWithToken:<accessKeyId>
  9. accessKeySecret:<accessKeySecret>
  10. secretToken:<secretToken>
  11. expireTime:<expireTime>]
  12. };
  13. OnUploadRertyListener testUploadRertyListener = ^{;};
  14. OnUploadRertyResumeListener testUploadRertyResumeListener = ^{;};
  15. VODUploadListener *listener;
  16. listener = [[VODUploadListener alloc] init];
  17. listener.started = testUploadStartedCallbackFunc;
  18. listener.success = testSuccessCallbackFunc;
  19. listener.failure = testFailedCallbackFunc;
  20. listener.progress = testProgressCallbackFunc;
  21. listener.expire = testTokenExpiredCallbackFunc;
  22. listener.retry = testUploadRertyListener;
  23. listener.retryResume = testUploadRertyResumeListener;
  24. // Get Token
  25. // Upload client initialization
  26. VODUploadClient *uploader;
  27. [uploader init:<accessKeyId>
  28. accessKeySecret:<accessKeySecret>
  29. secretToken:<secretToken>
  30. expireTime:<expireTime>
  31. listener:listener];
  32. // File added successfully
  33. [uploader addFile:<uploadFilePath>
  34. endpoint:<endpoint>
  35. bucket:<bucketName>
  36. object:<objectKey>];
  37. // Start uploading
  38. [uploader start];
Thank you! We've received your feedback.