Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon

graphicbeacon/main.dart

Last active Dec 31, 2019
Embed
What would you like to do?
"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

This comment has been minimized.

Copy link
Owner Author

@graphicbeacon graphicbeacon commented Dec 31, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.