4.dart_ 1.81 KB
class FileUploadScreen extends StatefulWidget {
  @override
  _FileUploadScreenState createState() => _FileUploadScreenState();
}

class _FileUploadScreenState extends State<FileUploadScreen> {
  final _uploader = MultiThreadedFileUploader();
  double _progress = 0.0;
  bool _isUploading = false;
  String _status = '准备就绪';

  Future<void> _uploadFile() async {
    setState(() {
      _isUploading = true;
      _progress = 0.0;
      _status = '开始上传...';
    });

    // 选择文件
    final file = await _pickFile();
    if (file == null) return;

    try {
      final summary = await _uploader.uploadFile(
        file,
        'https://api.example.com/upload-chunk',
        'https://api.example.com/merge-file',
      );

      setState(() {
        _status = summary.success 
            ? '上传成功! 耗时: ${summary.duration.inSeconds}秒'
            : '上传失败: ${summary.error}';
        _progress = 1.0;
      });

    } catch (e) {
      setState(() {
        _status = '上传异常: $e';
      });
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  }

  Future<File?> _pickFile() async {
    // 实现文件选择逻辑
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('多线程文件上传')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            LinearProgressIndicator(value: _progress),
            SizedBox(height: 20),
            Text(_status),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _isUploading ? null : _uploadFile,
              child: Text(_isUploading ? '上传中...' : '选择文件并上传'),
            ),
          ],
        ),
      ),
    );
  }
}