flutter 打开照片 裁剪 接入阿里云OSS

之前因为使用正常文件上传,用户多时拥堵无法正常上传,因此接入阿里OSS 来解决这个问题。本来打算整原生那块,看了下比较麻烦,用flutter dio 直接请求oss 完成

1.上传用到了image_picker 插件。这个比较简单了。

//要上传的文件,此处为从相册选择照片
showImagePicker(type) async {
var image = await ImagePicker.pickImage(
source: type == 1 ? ImageSource.camera : ImageSource.gallery);
_image = image;
_cropImage(_image);
}
//裁剪代码  
Future<void> _cropImage(File imageFile) async {
    File croppedFile = await ImageCropper.cropImage(
        sourcePath: imageFile.path,
        aspectRatioPresets: Platform.isAndroid
            ? [
                CropAspectRatioPreset.square,
                CropAspectRatioPreset.ratio3x2,
                CropAspectRatioPreset.original,
              ]
            : [
                CropAspectRatioPreset.original,
                CropAspectRatioPreset.square,
                CropAspectRatioPreset.ratio3x2,
                CropAspectRatioPreset.ratio4x3,
              ],
        androidUiSettings: AndroidUiSettings(
            toolbarTitle: '裁剪',
            toolbarColor: Colors.transparent,
            toolbarWidgetColor: Color(0xffff6633),
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: false),
        iosUiSettings: IOSUiSettings(
          title: '裁剪',
        ));
    if (croppedFile != null) {
      _imagePath = croppedFile;
      ossUrl = '';
      flieUpload(_imagePath);
    }
  }

  

2.阿里oss 配置以及相关处理String accesskey = '后台返回的AccessKeySecret'; 这个比较重要要用secret    print(accesskey);    //验证文本域    String policyText =

        '{"expiration": "2020-01-01T12:00:00.000Z","conditions": [["content-length-range", 0, 1048576000]]}';
    //进行utf8编码
    List<int> policyText_utf8 = utf8.encode(policyText);
    //进行base64编码
    String policy_base64 = base64.encode(policyText_utf8);
    //再次进行utf8编码
    List<int> policy = utf8.encode(policy_base64);
    //进行utf8 编码
    List<int> key = utf8.encode(accesskey);
    //通过hmac,使用sha1进行加密
    List<int> signature_pre = new Hmac(sha1, key).convert(policy).bytes;
    //最后一步,将上述所得进行base64 编码
    String signature = base64.encode(signature_pre);
    //dio的请求配置,这一步非常重要!
    BaseOptions options = new BaseOptions();
    options.responseType = ResponseType.plain;  这个后台返回值dio 默认json 要设置为普通文本

   //创建dio对象
    Dio dio = new Dio(options); 
    //文件名
    String fileName = _image.path
        .substring(_image.path.lastIndexOf("/") + 1, _image.path.length); 
//    生成uuid
    String uuid1 = uuid.v1();
    //创建一个formdata,作为dio的参数 2.0写法
    FormData data = new FormData.from({
      'Filename': 'img',
      'key': 'images/work/${uuid1}/img.' + fileName.split('.')[1],   //设置阿里oss 路径 不写就是默认根目录
      'policy': policy_base64,
      'OSSAccessKeyId': 'OSSAccessKeyId', 
    'success_action_status': '200', //让服务端返回200,不然,默认会返回204
    'signature': signature,
    'file': new UploadFileInfo(new File(_image.path), "imageFileName")
  });
// print(_image.path); //   
   //dio 3.0写法
   FormData data = new FormData.fromMap({
  'Filename': 'img',
    'key':
'images/avatar/${allString.substring(0, 3)}/${allString.substring(3, 6)}/${allString.substring(6, 9)}/${user_info['id']}-120-120-${showtime}.' +
fileName.split('.')[1],
  'policy': policy_base64,
  'OSSAccessKeyId': 'xxxxx',
  'success_action_status': '200', //让服务端返回200,不然,默认会返回204
  'signature': signature,
  'file': await MultipartFile.fromFile(_image.path,
filename: "image.$_contentType",
contentType: MediaType('image', '$_contentType')) //修改文件请求头
});
Response response; // Dio dio = new Dio(); // dio.options.baseUrl = DioUtil.API_PREFIX; 
dio.options.contentType = 'image/$_contentType';

setState(() { showPro
= true; });
try {
response
= await dio .post('http://lncc-public.oss-accelerate.aliyuncs.com', data: data,
onSendProgress: (
int sent, int total) { //进度设置
print(
"上传进度=======$sent $total");
if (sent == total) { print('百分之百');
setState(() { showPro
= false; Progress = 100; });
var obj = {'id': 'temp', 'work_url': _image.path};
uploadFileInfo.add(obj);
audioCache.play(
'collect/upload_01/00001.mp3', volume: 0.5);
setState(() { ifshow
= 1.0;
//动画以及声音设置
});
FlutterTimer.startTimerChanged( 
duration: _assetList.length, period: periodMilli, fromEnd:
false, counting: _animing, end: null);
Future.delayed(Duration(seconds:
4), () {
print(
'三秒后关闭');
FlutterTimer(context).release();
setState(() {
ifshow
= 0; Progress = 0;
});
});
}
else {
setState(() {
Progress
= int.parse(((sent / total) * 100).toStringAsFixed(0)); print(Progress); }); }
});
var result = response.statusCode;
if(result==200){
print(result);
var upurl = 'https://public-statics.lnart.com/images/work/${uuid1}/img.'+ fileName.split('.')[1]; print(upurl); //将上传oss的路径上传到自己的服务器
setState(() { showPro
= false; });
}
} on DioError
catch (e) {
print(e.message);
print(e.response.data);
print(e.response.headers);
print(e.response.request);
}

原文地址:https://www.cnblogs.com/wupeng88/p/11799450.html