flutter Upload files directly to Alibaba Cloud oss

  • 2021-12-13 09:11:11
  • OfStack

Directory code implementation Example of calling upload
Another way to prepare: Give a tool class

Code implementation

The following is a class I wrote to upload oss, which can be uploaded directly only by replacing the parameters of ossAccessKeyId, ossAccessKeySecret, bucket, url and expiration


import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';

class UploadOss {

  static String ossAccessKeyId = 'ossAccessKeyId';

  static String ossAccessKeySecret = 'ossAccessKeySecret';
  // oss Set bucket The name of 
  static String bucket = 'bucketName';
  //  Sending the requested url, According to which city you set it up 
  static String url = 'https://$bucket.oss-cn-hangzhou.aliyuncs.com';

  //  Expired time 
  static String expiration = '2025-01-01T12:00:00.000Z';

  /**
   * @params file  File object to upload 
   * @params rootDir  Alibaba Cloud oss Root folder name set 
   * @param fileType  File types such as jpg,mp4 Etc 
   * @param callback  Callback function I use here to pass cancelToken Which facilitates late closure requests 
   * @param onSendProgress  Uploaded progress events 
   */

  static Future<String> upload({ File file , String rootDir = 'moment', String fileType, Function callback, Function onSendProgress}) async {
    String policyText = '{"expiration": "$expiration","conditions": [{"bucket": "$bucket" },["content-length-range", 0, 1048576000]]}';

    //  Get a signature 
    String signature = getSignature(policyText);

    BaseOptions options = new BaseOptions();
    options.responseType = ResponseType.plain;

    // Create dio Object 
    Dio dio = new Dio(options);
    //  Generate oss The path and file name I currently set here is moment/20201229/test.mp4
    String pathName = '$rootDir/${getDate()}/${getRandom(12)}.${fileType == null ? getFileType(file.path) : fileType}';

    //  Object of the request parameter form Object 
    FormData data = new FormData.fromMap({
      'key': pathName,
      'policy': getSplicyBase64(policyText),
      'OSSAccessKeyId': ossAccessKeyId,
      'success_action_status': '200', // Let the server return 200 Otherwise, the default returns 204
      'signature': signature,
      'contentType': 'multipart/form-data',
      'file': MultipartFile.fromFileSync(file.path),
    });

    Response response;
    CancelToken uploadCancelToken = CancelToken();
    callback ?? callback(uploadCancelToken);

    try {
      //  Send a request 
      response = await dio.post(url, data: data, cancelToken: uploadCancelToken, onSendProgress: (int count, int data) {
        onSendProgress(count, data);
      });
      //  Return to the file access path after success 
      return '$url/$pathName';
    } catch(e) {
      throw(e.message);
    }

  }


  /*
  *  Generate a random string of fixed length 
  * */
  static String getRandom(int num) {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    String left = '';
    for (var i = 0; i < num; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }
  /*
  *  Get the picture name according to the local path of the picture 
  * */
  static String getImageNameByPath(String filePath) {
    // ignore: null_aware_before_operator
    return filePath?.substring(filePath?.lastIndexOf("/")+1,filePath?.length);
  }
  /**
   *  Get the file type 
   */
  static String getFileType(String path) {
    print(path);
    List<String> array = path.split('.');
    return array[array.length -1];
  }
  ///  Get Date 
  static String getDate() {
    DateTime now = DateTime.now();
    return '${now.year}${now.month}${now.day}';
  }

  //  Get plice Adj. base64
  static getSplicyBase64(String policyText) {
    // Go on utf8 Code 
    List<int> policyText_utf8 = utf8.encode(policyText);
    // Go on base64 Code 
    String policy_base64 = base64.encode(policyText_utf8);
    return policy_base64;
  }

  ///  Get a signature 
  static String getSignature(String policyText) {
    // Go on utf8 Code 
    List<int> policyText_utf8 = utf8.encode(policyText);
    // Go on base64 Code 
    String policy_base64 = base64.encode(policyText_utf8);
    // Go on again utf8 Code 
    List<int> policy = utf8.encode(policy_base64);
    // Go on utf8  Code 
    List<int> key = utf8.encode(ossAccessKeySecret);
    // Pass hmac, Use sha1 Encrypt 
    List<int> signature_pre = Hmac(sha1, key).convert(policy).bytes;
    // Finally 1 Step of carrying out the above obtained base64  Code 
    String signature = base64.encode(signature_pre);
    return signature;
  }
}

Example of calling upload

Other counselors upload them according to their own situation


Future<String> uploadFile(File file, { Function onSendProgress, Function callback}) async {
  final String url = await UploadOss.upload(file: file, onSendProgress: onSendProgress, callback: callback);
  return url;
}

Another method

At present, Ali does not have an official SDK for Flutter to integrate, but some people upload Flutter with a packaging library https://pub.dev/packages/aly_oss #-example-tab-, so we can only upload it in the form of post submission;

Preparations:

1. Obtain the OSS certificate address (your oss _sts _server), and notify get to directly obtain static String ossServerUrl = 'http://../sts-server/sts. php';

2. Uploaded storage address (bucket name): static String ossEndPointCdn = ' < your endpointcdn > ';


//  Pass ossServerUrl Direct get The following data is obtained 
{
        "StatusCode": 200,
          "AccessKeyId": "STS.NSsrKZes4cqm.....",
          "AccessKeySecret": "7eGnLZaEFsRCGYJAnrtdE9n.....",
          "Expiration": "2020-04-08T03:44:21Z",
          "SecurityToken": "CAISlQJ1q6Ft5B2y....."
  }
 
// Parameters required by the form : AccessKeyId , AccessKeySecret , SecurityToken;
FormData formdata = new FormData.from({
        // File name, optional 
        'Filename': OssUtil.instance.getImageName(filePath),
        //" You can fill in the folder name (corresponding to the oss Folders in the service) /" + fileName
        'key': uploadName,// File name after uploading 
        'policy': OssUtil.policy,
        //Bucket  Owner's AccessKeyId . 
        'OSSAccessKeyId': data['AccessKeyId'],
        // Let the server return 200 Otherwise, the default returns 204
        'success_action_status': '200',
        'signature': OssUtil.instance.getSignature(data['AccessKeySecret']),
        // Temporary user authorization must be carried back in the background security-token
        'x-oss-security-token': data['SecurityToken'],
        'file': new UploadFileInfo(
            file, OssUtil.instance.getImageNameByPath(filePath))
        // Must be placed at the end of the parameter 
   });
// Then put the form directly through the storage address (formdata) Upload ;
Dio dio=Dio();
dio.options.responseType=ResponseType.plain;
Response response=awaitdio.post(<ossEndPointCdn>,data:formData);
......

tips: After successful upload, the picture address imageUrl = ossEndPointCdn + '/' + uploadName;

Give 1 tool class


import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'dart:math';
 
class OssUtil {
  Get 
  // Validate a text field 
  static String _policyText =
      '{"expiration": "2069-05-22T03:15:00.000Z","conditions": [["content-length-range", 0, 1048576000]]}';//UTC Time +8= Beijing time 
 
  // Go on utf8 Code 
  // ignore: non_constant_identifier_names
  static List<int> _policyText_utf8 = utf8.encode(_policyText);
  // Go on base64 Code 
  static String policy= base64.encode(_policyText_utf8);
 
  // Go on again utf8 Code 
  // ignore: non_constant_identifier_names
  static List<int> _policy_utf8 = utf8.encode(policy);
 
  //  Factory model 
  factory OssUtil() => _getInstance();
 
  static OssUtil get instance => _getInstance();
  static OssUtil _instance;
 
  OssUtil._internal();
 
  static OssUtil _getInstance() {
    if (_instance == null) {
      _instance = new OssUtil._internal();
    }
    return _instance;
  }
 
  /*
  * Get signature Signature parameter 
  */
  String getSignature(String _accessKeySecret){
    // Go on utf8  Code 
    // ignore: non_constant_identifier_names
    List<int> AccessKeySecretUtf8 = utf8.encode(_accessKeySecret);
    // Pass hmac, Use sha1 Encrypt 
    List<int> signaturePre = new Hmac(sha1, AccessKeySecretUtf8).convert(_policy_utf8).bytes;
    // Finally 1 Step of carrying out the above obtained base64  Code 
    String signature = base64.encode(signaturePre);
    return signature;
  }
 
  // ignore: slash_for_doc_comments
  /**
   *  Generate the name of the uploaded picture  , Format obtained :photo/20171027175940_oCiobK
   *  You can define the upload path uploadPath(Oss The name of the save folder in the )
   * @param uploadPath  Upload path   Such as: /photo
   * @return photo/20171027175940_oCiobK
   */
  String getImageUploadName(String uploadPath,String filePath) {
    String imageMame = "";
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    imageMame =timestamp.toString()+"_"+getRandom(6);
    if(uploadPath!=null&&uploadPath.isNotEmpty){
      imageMame=uploadPath+"/"+imageMame;
    }
    String imageType=filePath?.substring(filePath?.lastIndexOf("."),filePath?.length);
    return imageMame+imageType;
  }
 
  String getImageName(String filePath) {
    String imageMame = "";
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    imageMame =timestamp.toString()+"_"+getRandom(6);
    String imageType=filePath?.substring(filePath?.lastIndexOf("."),filePath?.length);
    return imageMame+imageType;
  }
 
  /*
  *  Generate a random string of fixed length 
  * */
  String getRandom(int num) {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    String left = '';
    for (var i = 0; i < num; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }
 
  /*
  *  Get the picture name according to the local path of the picture 
  * */
  String getImageNameByPath(String filePath) {
    // ignore: null_aware_before_operator
    return filePath?.substring(filePath?.lastIndexOf("/")+1,filePath?.length);
  }
}

The above is flutter upload files directly to Alibaba Cloud oss implementation steps of the details, more about flutter upload files to Alibaba Cloud oss information please pay attention to other related articles on this site!


Related articles: