最近在搞flutter的大文件上传功能,记录一下断点续传的视线
1.将文件进行分块,我们和后台约定的是3M每块
static const int partSize = 1024 * 1024 * 3; //3m每块
///上传文件 后台要记录从第几块开始传,也就是currentPart
Future<bool> _uploadZip(String path) async {
File file = File(path);
String fileName = FileUtil.getBaseName(file.path);
int fileSize = file.lengthSync(); //文件总大小
int totalPart = (fileSize * 1.0 / partSize).ceil(); //分块总数 向上取整
int currentPart = currentPart; //当前要传第几块 由后台记录返回的
//开启循环上传每一块
while (currentPart < totalPart) {
bool isOK = await _uploadPart(file, currentPart, totalPart, fileSize, fileName);
if (!isOK) {
invokeStateListener(ProgressState.error, null);
return false;
}
//更新进度
invokeProgressListeners((currentPart + 1) * 1.0 / totalPart);
currentPart++;
}
//所有分快上传成功
invokeStateListener(ProgressState.complete, null);
return true;
}
2.将每一个分块上传到后台,并记录上传是否成功
Future<bool> _uploadPart(File file, int currentPart, int totalPart, int fileSize, String fileName) async {
//开始读文件的位置
int start = currentPart * partSize;
//读取文件的长度 注意不要让长度超过总长度
var length = (start + partSize > fileSize) ? (fileSize - start) : partSize;
RandomAccessFile raf = file.openSync(mode: FileMode.read);
raf.setPositionSync(start);
Uint8List data = raf.readSync(length);//从文件总长度中截取出要上传的长度
Map<String, dynamic> map = {};
map['total'] = totalPart; //总块数
map['currentPart'] = currentPart; //当前上传到第几块
map['part'] = MultipartFile.fromBytes(data, filename:'随便设置文件名');//当前快的数据
Map<String, dynamic>? response = await 真正的上传函数
//自定义逻辑 失败的话返回false
return true;
}
网友评论