Skip to content

Instantly share code, notes, and snippets.

Last active April 3, 2023 09:29
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
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') {
..headers.contentType = ContentType.html
<title>Image Upload Server</title>
<form method="post" action="/fileupload" enctype="multipart/form-data">
<input type="file" name="fileupload" /><br /><br />
<button type="submit">Upload to server</button>
} else {
// accessing /fileupload endpoint
List<int> dataBytes = [];
await for (var data in request) {
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) {
final contentDisposition = part.headers['content-disposition'];
final filename = RegExp(r'filename="([^"]*)"')
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
author: Jermaine Oppong
sdk: '>=2.5.0 <3.0.0'
path: ^1.6.0
mime: ^0.9.6+3 # We need this package here.
pedantic: ^1.8.0
test: ^1.6.0
Copy link

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