File Upload and Download
Uploading and downloading files are common tasks in API-driven apps, enabling users to share images, documents, or media, and to retrieve resources from a server. File upload involves sending files from the device to a remote server, while file download retrieves files from the server to the device. These operations are essential for features such as profile photo updates, downloading reports, or sharing media files with others. Since file transfers can take time, especially with large files or slow connections, it is important to provide users with visual feedback on the progress of these operations.
main.dart
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; void main() async { // Example file paths (replace with actual file paths on your device) final uploadFilePath = 'example_upload.txt'; final downloadUrl = 'https://example.com/file-to-download.txt'; final saveDownloadPath = 'downloaded_file.txt'; // Create a dummy file to upload await File(uploadFilePath).writeAsString('Sample file content for upload.'); print('Uploading file...'); await uploadFileWithProgress(uploadFilePath, 'https://example.com/upload'); print('\nDownloading file...'); await downloadFileWithProgress(downloadUrl, saveDownloadPath); } Future<void> uploadFileWithProgress(String filePath, String url) async { final file = File(filePath); final totalBytes = await file.length(); int bytesSent = 0; final request = http.MultipartRequest('POST', Uri.parse(url)); final stream = http.ByteStream(file.openRead().transform( StreamTransformer.fromHandlers( handleData: (data, sink) { bytesSent += data.length; _printProgress(bytesSent, totalBytes, 'Upload'); sink.add(data); }, ), )); final multipartFile = http.MultipartFile( 'file', stream, totalBytes, filename: file.uri.pathSegments.last, ); request.files.add(multipartFile); final response = await request.send(); if (response.statusCode == 200) { print('\nFile uploaded successfully.'); } else { print('\nFile upload failed with status: ${response.statusCode}'); } } Future<void> downloadFileWithProgress(String url, String savePath) async { final response = await http.Client().send(http.Request('GET', Uri.parse(url))); final contentLength = response.contentLength ?? 0; int bytesReceived = 0; final file = File(savePath); final sink = file.openWrite(); await response.stream.listen( (chunk) { bytesReceived += chunk.length; _printProgress(bytesReceived, contentLength, 'Download'); sink.add(chunk); }, onDone: () async { await sink.close(); print('\nFile downloaded successfully.'); }, onError: (e) async { await sink.close(); print('\nFile download failed: $e'); }, cancelOnError: true, ).asFuture(); } void _printProgress(int processed, int total, String label) { if (total == 0) return; final percent = (processed / total * 100).toStringAsFixed(1); stdout.write('\r$label Progress: $percent%'); }
Progress indicators are updated by tracking the number of bytes sent or received relative to the total file size. During upload, each chunk of data read from the file increments a counter, and the progress is printed as a percentage. Similarly, during download, each chunk received from the server increases the received byte count, and the percentage is displayed in real time. This keeps users informed about how much of the file transfer is complete.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 6.67
File Upload and Download
Swipe to show menu
Uploading and downloading files are common tasks in API-driven apps, enabling users to share images, documents, or media, and to retrieve resources from a server. File upload involves sending files from the device to a remote server, while file download retrieves files from the server to the device. These operations are essential for features such as profile photo updates, downloading reports, or sharing media files with others. Since file transfers can take time, especially with large files or slow connections, it is important to provide users with visual feedback on the progress of these operations.
main.dart
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; void main() async { // Example file paths (replace with actual file paths on your device) final uploadFilePath = 'example_upload.txt'; final downloadUrl = 'https://example.com/file-to-download.txt'; final saveDownloadPath = 'downloaded_file.txt'; // Create a dummy file to upload await File(uploadFilePath).writeAsString('Sample file content for upload.'); print('Uploading file...'); await uploadFileWithProgress(uploadFilePath, 'https://example.com/upload'); print('\nDownloading file...'); await downloadFileWithProgress(downloadUrl, saveDownloadPath); } Future<void> uploadFileWithProgress(String filePath, String url) async { final file = File(filePath); final totalBytes = await file.length(); int bytesSent = 0; final request = http.MultipartRequest('POST', Uri.parse(url)); final stream = http.ByteStream(file.openRead().transform( StreamTransformer.fromHandlers( handleData: (data, sink) { bytesSent += data.length; _printProgress(bytesSent, totalBytes, 'Upload'); sink.add(data); }, ), )); final multipartFile = http.MultipartFile( 'file', stream, totalBytes, filename: file.uri.pathSegments.last, ); request.files.add(multipartFile); final response = await request.send(); if (response.statusCode == 200) { print('\nFile uploaded successfully.'); } else { print('\nFile upload failed with status: ${response.statusCode}'); } } Future<void> downloadFileWithProgress(String url, String savePath) async { final response = await http.Client().send(http.Request('GET', Uri.parse(url))); final contentLength = response.contentLength ?? 0; int bytesReceived = 0; final file = File(savePath); final sink = file.openWrite(); await response.stream.listen( (chunk) { bytesReceived += chunk.length; _printProgress(bytesReceived, contentLength, 'Download'); sink.add(chunk); }, onDone: () async { await sink.close(); print('\nFile downloaded successfully.'); }, onError: (e) async { await sink.close(); print('\nFile download failed: $e'); }, cancelOnError: true, ).asFuture(); } void _printProgress(int processed, int total, String label) { if (total == 0) return; final percent = (processed / total * 100).toStringAsFixed(1); stdout.write('\r$label Progress: $percent%'); }
Progress indicators are updated by tracking the number of bytes sent or received relative to the total file size. During upload, each chunk of data read from the file increments a counter, and the progress is printed as a percentage. Similarly, during download, each chunk received from the server increases the received byte count, and the percentage is displayed in real time. This keeps users informed about how much of the file transfer is complete.
Thanks for your feedback!