之前因為使用正常文件上傳,用戶多時擁堵無法正常上傳,因此接入阿里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);
}