# Implement your own File upload server

In this tutorial we will learn how to extract file data sent via a form and persist that to server’s filesystem. We will learn more about the multipart/form-data content type and how to use the [mime](https://pub.dev/packages/mime) package to extract images from our payload. Some great tips in this lesson so watch till the end!!!

## Watch video tutorial

%[https://youtu.be/hSkD3y9HMro] 

## **Set up the project**

Create a project folder and bootstrap a console-based project using Stagehand:

```bash
$ stagehand console-full
```

Open the **pubspec.yaml** file and add a dependency for the **mime** package:

```yaml
dependencies:
  mime: ^0.9.6+3
```

Update your dependencies by running `pub get` in your terminal.

Below is the solution from the video tutorial:

```dart
// 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();
  });
}
```

[Get the source code](https://gist.github.com/graphicbeacon/c25ffe49dade93003742bc43cc21147b)
