Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Last active April 3, 2023 09:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save graphicbeacon/c25ffe49dade93003742bc43cc21147b to your computer and use it in GitHub Desktop.
Save graphicbeacon/c25ffe49dade93003742bc43cc21147b to your computer and use it in GitHub Desktop.
"Dart File Upload Server Tutorial" solution for YouTube video tutorial
// bin/main.dart
import 'dart:io';
import 'package:mime/mime.dart';
main() async {
var server = await HttpServer.bind('localhost', 8085);
server.listen((request) async {
if (request.uri.path != '/fileupload') {
request.response
..headers.contentType = ContentType.html
..write('''
<html>
<head>
<title>Image Upload Server</title>
</head>
<body>
<form method="post" action="/fileupload" enctype="multipart/form-data">
<input type="file" name="fileupload" /><br /><br />
<button type="submit">Upload to server</button>
</form>
</body>
</html>
''');
} else {
// accessing /fileupload endpoint
List<int> dataBytes = [];
await for (var data in request) {
dataBytes.addAll(data);
}
String boundary = request.headers.contentType.parameters['boundary'];
final transformer = MimeMultipartTransformer(boundary);
final uploadDirectory = './upload';
final bodyStream = Stream.fromIterable([dataBytes]);
final parts = await transformer.bind(bodyStream).toList();
for (var part in parts) {
print(part.headers);
final contentDisposition = part.headers['content-disposition'];
final filename = RegExp(r'filename="([^"]*)"')
.firstMatch(contentDisposition)
.group(1);
final content = await part.toList();
if (!Directory(uploadDirectory).existsSync()) {
await Directory(uploadDirectory).create();
}
await File('$uploadDirectory/$filename').writeAsBytes(content[0]);
}
}
await request.response.close();
});
}
name: image_upload_server
description: A sample command-line application.
version: 1.0.0
homepage: https://www.creativebracket.com
author: Jermaine Oppong
environment:
sdk: '>=2.5.0 <3.0.0'
dependencies:
path: ^1.6.0
mime: ^0.9.6+3 # We need this package here.
dev_dependencies:
pedantic: ^1.8.0
test: ^1.6.0
@graphicbeacon
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment