Last active
July 10, 2022 15:52
-
-
Save lslv1243/1036364b10c6578d969cb4ed2d7eba42 to your computer and use it in GitHub Desktop.
simple dart file upload server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:mime/mime.dart'; | |
void main(List<String> arguments) async { | |
const port = 8080; | |
var lastId = (await _loadLastId()) ?? -1; | |
final server = await HttpServer.bind(InternetAddress.anyIPv4, port); | |
server.listen((request) async { | |
void close(int statusCode) { | |
request.response.statusCode = 404; | |
request.response.close(); | |
} | |
if (request.uri.path != '/screenshot' || request.method != 'POST') { | |
close(404); | |
return; | |
} | |
try { | |
final boundary = request.headers.contentType!.parameters['boundary']!; | |
final mimeTransformer = MimeMultipartTransformer(boundary); | |
final parts = request.cast<List<int>>().transform(mimeTransformer); | |
final part = await parts.first; | |
final file = File('uploaded_files/${++lastId}.png'); | |
final write = file.openWrite(); | |
await part.pipe(write); | |
await write.close(); | |
await _storeLastId(lastId); | |
close(200); | |
} catch (_) { | |
close(500); | |
} | |
}); | |
print('screenshot server listening on $port.'); | |
} | |
final _lastIdFile = File('uploaded_files/.last_id'); | |
Future<int?> _loadLastId() async { | |
final exists = await _lastIdFile.exists(); | |
if (!exists) return null; | |
final contents = await _lastIdFile.readAsString(); | |
return int.tryParse(contents); | |
} | |
Future<void> _storeLastId(int id) async { | |
_lastIdFile.writeAsString(id.toString()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment