最近呢,由于工作需要,然后之网上也找了一些博客资料。总觉得实现起来有很多问题。下面分享下我到一个完整例子。

 1.插件安装

dio: ^2.1.13
image_picker: ^0.6.0+1

2.准备阿里云oss信息

accessKey 和AccessKeySecret

3下面我就在2个方法里面实现拍照上传到功能

 

/   //拍照
  _takePhoto() async {
    var image = await ImagePicker.pickImage(
        source: ImageSource.camera, maxWidth: 400); //maxWidth: 400剪切操作
    setState(() {
      this._image = image;
    });
    //调用图片上传
    this.uploadImage(this._image);
  }

//上传图片
  uploadImage(File file) async {
   

//验证文本域 这里设置是过期时间
    String policyText =
        '{"expiration": "2090-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 1048576000]]}';

//进行utf8编码
    List<int> policyTextUtf8 = utf8.encode(policyText);

//进行base64编码
    String policyBase64 = base64.encode(policyTextUtf8);

//再次进行utf8编码
    List<int> policy = utf8.encode(policyBase64);

    String accesskey = '你自己的accesskeysecret';

//进行utf8 编码
    List<int> key = utf8.encode(accesskey);

//通过hmac,使用sha1进行加密
    List<int> signaturePre = new Hmac(sha1, key).convert(policy).bytes;

//最后一步,将上述所得进行base64 编码
    String signature = base64.encode(signaturePre);

    //创建dio对象
    Dio dio = new Dio();
    //dio的请求配置
    dio.options.responseType = ResponseType.plain;
    //  dio.options.contentType = ContentType.parse("image/jpg");
    dio.options.contentType = ContentType.parse("multipart/form-data");
    //上传到文件名
    String fileName = _image.path
        .substring(_image.path.lastIndexOf("/") + 1, _image.path.length);
//创建一个formdata,作为dio的参数
    FormData data = new FormData.from({
      'Filename': 'ddd.jpg',
      'key': "images/" + fileName,
      'policy': policyBase64,
      'OSSAccessKeyId': "你自己的id",
      'success_action_status': '200', //让服务端返回200,不然,默认会返回204
      'signature': signature,
      'file': new UploadFileInfo(file, "imageFileName")
    });

    try {
      Response response = await dio
          .post("http://wangnode.oss-cn-beijing.aliyuncs.com", data: data);
      if (response.statusCode == 200) {
        print(response.headers);
        print(response.data);
        print(
            "https://wangnode.oss-cn-beijing.aliyuncs.com/images/" + fileName);
        setState(() {
          pimg =
              "https://wangnode.oss-cn-beijing.aliyuncs.com/images/" + fileName;
        });
      }
    } on DioError catch (e) {
      print(e.message);
      print(e.response.data);
      print(e.response.headers);
      print(e.response.request);
      print(accesskey);
    }
  }

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐