zsw
4 months ago
12 changed files with 179 additions and 101 deletions
@ -0,0 +1,80 @@
|
||||
|
||||
|
||||
|
||||
import 'dart:io'; |
||||
|
||||
import 'package:dio/dio.dart'; |
||||
import 'package:flutter/cupertino.dart'; |
||||
import 'package:huixiang/constant.dart'; |
||||
import 'package:huixiang/retrofit/data/base_data.dart'; |
||||
import 'package:huixiang/retrofit/retrofit_api.dart'; |
||||
import 'package:path_provider/path_provider.dart'; |
||||
import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart'; |
||||
|
||||
class Qiniu { |
||||
|
||||
|
||||
Storage storage = Storage(config: Config()); |
||||
PutController putController = PutController(); |
||||
|
||||
progressListener() { |
||||
// 添加任务进度监听 |
||||
putController.addProgressListener((double percent) { |
||||
print('任务进度变化:已发送:$percent'); |
||||
}); |
||||
|
||||
// 添加文件发送进度监听 |
||||
putController.addSendProgressListener((double percent) { |
||||
print('已上传进度变化:已发送:$percent'); |
||||
}); |
||||
|
||||
// 添加任务状态监听 |
||||
putController.addStatusListener((StorageStatus status) { |
||||
print('状态变化: 当前任务状态:$status'); |
||||
}); |
||||
|
||||
} |
||||
|
||||
Future<String> uploadFile(ApiService apiService, String filePath) async { |
||||
|
||||
String token = await _getToken(apiService); |
||||
|
||||
File file = File(filePath); |
||||
|
||||
PutResponse putResponse = await storage.putFile(file, token, options: PutOptions( |
||||
controller: putController, |
||||
key: filePath.split('/').last, |
||||
)); |
||||
|
||||
debugPrint("qiniuToken-result: ${putResponse.toJson()}"); |
||||
|
||||
return "$chatImageHost/${putResponse.key}"; |
||||
} |
||||
|
||||
Future<String> _getToken(ApiService apiService) async { |
||||
BaseData<String> baseData = await apiService.getQiniuToken() |
||||
.catchError((error){ |
||||
debugPrint("getQiniuToken: $error"); |
||||
}); |
||||
if (baseData.isSuccess) { |
||||
return baseData.data; |
||||
} else { |
||||
debugPrint("get token fail, check network"); |
||||
throw Error(); |
||||
} |
||||
} |
||||
|
||||
Dio dio = Dio(); |
||||
|
||||
Future<String> downloadFile(String urlPath) async { |
||||
Directory dir = await getTemporaryDirectory(); |
||||
File newFile = File("${dir.path}/hx_${urlPath.split('/').last}"); |
||||
Response response = await dio.download(urlPath, newFile.path); |
||||
if (response.statusCode == 200) { |
||||
return newFile.path; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
} |
||||
|
Loading…
Reference in new issue