56 lines
1.6 KiB
Dart
56 lines
1.6 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:app/config/config.dart';
|
|
import 'package:app/request/api/common_api.dart';
|
|
import 'package:app/request/dto/common/qiu_token_dto.dart';
|
|
import 'package:crypto/crypto.dart';
|
|
import 'package:dio/dio.dart';
|
|
import 'package:flutter_easyloading/flutter_easyloading.dart';
|
|
|
|
class QinUpload {
|
|
///获取七牛token
|
|
static Future<QiuTokenDto> _getQiuToken(File file, String path) async {
|
|
// 读取文件的字节数据
|
|
final fileBytes = await file.readAsBytes();
|
|
String fileMd5 = md5.convert(fileBytes).toString();
|
|
//前缀
|
|
var prefix = Config.getEnv() == "dev" ? "test" : "release";
|
|
var suffix = file.path.split(".").last;
|
|
|
|
var res = await getQiuTokenApi(
|
|
"xueguang/$prefix/$path/$fileMd5.$suffix",
|
|
);
|
|
return res;
|
|
}
|
|
|
|
///上传文件
|
|
/// - [file] 文件
|
|
/// - [path] 目标目录
|
|
static Future<String?> upload({
|
|
required File file,
|
|
required String path,
|
|
}) async {
|
|
var qiuToken = await _getQiuToken(file, path);
|
|
//数据
|
|
FormData formData = FormData.fromMap({
|
|
"file": await MultipartFile.fromFile(file.path),
|
|
"token": qiuToken.upToken,
|
|
"fname": qiuToken.fileKey,
|
|
"key": qiuToken.fileKey,
|
|
});
|
|
try {
|
|
Dio dio = Dio();
|
|
Response response = await dio.post(
|
|
qiuToken.uploadUrl!,
|
|
data: formData,
|
|
onSendProgress: (int sent, int total) {},
|
|
);
|
|
String key = response.data['key'];
|
|
return "https://${qiuToken.domain}/$key";
|
|
} catch (e) {
|
|
EasyLoading.showError("上传失败");
|
|
return null;
|
|
}
|
|
}
|
|
}
|