File uploads

suggest change

Uploading a file over HTTP almost always means one of two things:

This article shows both sides in Dart:

Packages used:

dart pub add http http_parser mime path shelf shelf_router shelf_multipart

The examples were run with Dart 3.13, http 1.6.0, mime 2.1.0, shelf 1.4.3, shelf_router 1.1.5 and shelf_multipart 2.0.1.

What a multipart request looks like

http.MultipartRequest builds the body for you, but it helps to see it once. finalize() is what send() calls internally to produce the body stream, so we can call it ourselves and print the result:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

Future<void> main() async {
  final request = http.MultipartRequest(
    'POST',
    Uri.parse('http://localhost:8080/upload'),
  );
  request.fields['title'] = 'Holiday notes';
  request.files.add(http.MultipartFile.fromString(
    'document',
    'Day 1: arrived.\nDay 2: beach.',
    filename: 'notes.txt',
  ));
  request.files.add(http.MultipartFile.fromBytes(
    'thumbnail',
    ascii.encode('GIF89a'),
    filename: 'thumb.gif',
    contentType: MediaType('image', 'gif'),
  ));

  // finalize() builds the body. Normally send() calls it for you.
  final body = await request.finalize().bytesToString(latin1);
  print('Content-Type: ${request.headers['content-type']}');
  print('Content-Length: ${request.contentLength}');
  print('');
  print(body);
}

Output (line endings are actually \r\n):

Content-Type: multipart/form-data; boundary=dart-http-boundary-k2YXoUKfceteafO8AmZ3KbsT2ZSr.pQ8adq1tf4oTpZy2iG_Zvi
Content-Length: 613

--dart-http-boundary-k2YXoUKfceteafO8AmZ3KbsT2ZSr.pQ8adq1tf4oTpZy2iG_Zvi
content-disposition: form-data; name="title"

Holiday notes
--dart-http-boundary-k2YXoUKfceteafO8AmZ3KbsT2ZSr.pQ8adq1tf4oTpZy2iG_Zvi
content-type: text/plain; charset=utf-8
content-disposition: form-data; name="document"; filename="notes.txt"

Day 1: arrived.
Day 2: beach.
--dart-http-boundary-k2YXoUKfceteafO8AmZ3KbsT2ZSr.pQ8adq1tf4oTpZy2iG_Zvi
content-type: image/gif
content-disposition: form-data; name="thumbnail"; filename="thumb.gif"

GIF89a
--dart-http-boundary-k2YXoUKfceteafO8AmZ3KbsT2ZSr.pQ8adq1tf4oTpZy2iG_Zvi--

The structure:

The filename and the part's content-type are chosen by the client. A server must treat both as untrusted hints.

Uploading files with package:http

MultipartFile has four ways to create a part:

Constructor Use for
MultipartFile.fromPath(field, path) a file on disk. Streams it, filename defaults to the file's base name
MultipartFile.fromBytes(field, bytes) data already in memory, e.g. a generated image or bytes from a Flutter file picker on the web
MultipartFile.fromString(field, text) text, encoded as UTF-8 with text/plain; charset=utf-8
MultipartFile(field, stream, length) any Stream<List<int>> whose length you know

The default content type for files is application/octet-stream. Pass contentType: MediaType(...) from package:http_parser if the server cares about it. lookupMimeType(path) from package:mime can guess it from the extension.

fromPath uses dart:io, so it doesn't work in the browser. In Flutter web use fromBytes.

The next program starts a tiny server with dart:io (explained in the next section) and uploads a 3 MB file with two text fields:

import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';

final uploadDir = Directory('uploads');

Future<void> handleUpload(HttpRequest request) async {
  final contentType = request.headers.contentType;
  final boundary = contentType?.parameters['boundary'];
  if (request.method != 'POST' ||
      contentType?.mimeType != 'multipart/form-data' ||
      boundary == null) {
    request.response.statusCode = HttpStatus.badRequest;
    await request.response.close();
    return;
  }

  final fields = <String, String>{};
  final files = <Map<String, Object>>[];

  final parts = MimeMultipartTransformer(boundary).bind(request);
  await for (final part in parts) {
    final disposition = HeaderValue.parse(part.headers['content-disposition']!);
    final name = disposition.parameters['name']!;
    final filename = disposition.parameters['filename'];

    if (filename == null) {
      // A regular form field: small, read it into memory.
      fields[name] = await utf8.decodeStream(part);
      continue;
    }

    // A file: stream it to disk chunk by chunk.
    final file = File('${uploadDir.path}/${DateTime.now().microsecondsSinceEpoch}.bin');
    final sink = file.openWrite();
    await part.pipe(sink); // pipe() closes the sink when done
    files.add({
      'field': name,
      'filename': filename,
      'contentType': part.headers['content-type'] ?? 'unknown',
      'size': await file.length(),
      'savedAs': file.path,
    });
  }

  request.response.headers.contentType = ContentType.json;
  request.response.write(jsonEncode({'fields': fields, 'files': files}));
  await request.response.close();
}

Future<void> main() async {
  await uploadDir.create();
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen(handleUpload);
  print('Listening on port ${server.port}');

  // Create a 3 MB test file.
  final report = File('report.pdf');
  await report.writeAsBytes(List.filled(3 * 1024 * 1024, 42));

  // Upload it, together with two text fields.
  final request = http.MultipartRequest(
    'POST',
    Uri.parse('http://localhost:${server.port}/upload'),
  )
    ..fields['author'] = 'Alice'
    ..fields['comment'] = 'Q3 numbers'
    ..files.add(await http.MultipartFile.fromPath(
      'attachment',
      report.path,
      contentType: MediaType('application', 'pdf'),
    ));

  final streamed = await request.send();
  final response = await http.Response.fromStream(streamed);
  print('Status: ${response.statusCode}');
  print(const JsonEncoder.withIndent('  ').convert(jsonDecode(response.body)));

  await server.close();
}

Output:

Listening on port 57485
Status: 200
{
  "fields": {
    "author": "Alice",
    "comment": "Q3 numbers"
  },
  "files": [
    {
      "field": "attachment",
      "filename": "report.pdf",
      "contentType": "application/pdf",
      "size": 3145728,
      "savedAs": "uploads/1792265186694752.bin"
    }
  ]
}

Client-side notes:

Receiving uploads with dart:io

The server above uses only dart:io plus package:mime:

  1. Get the boundary parameter from the request's Content-Type.
  2. MimeMultipartTransformer(boundary).bind(request) turns the request byte stream into a Stream<MimeMultipart>. Each MimeMultipart has headers and is itself a Stream<List<int>> of that part's bytes.
  3. Parse Content-Disposition with HeaderValue.parse() to get name and filename. A part with a filename is a file, the rest are text fields.
  4. Read text fields into memory, and pipe files to disk.

Parts arrive in order, and each part must be fully read (or drained) before the next one is delivered. That's what makes streaming possible: memory use stays at a few 64 KB chunks no matter how big the files are. It also means you can't, for example, read the third part first.

Receiving uploads with Shelf

With Shelf, package:shelf_multipart adds two extension methods to Request:

Each FormData has name, filename (null for plain fields) and part. part is a byte stream with readString() and readBytes() helpers.

The server below is closer to what you'd deploy. It:

import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:mime/mime.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_multipart/shelf_multipart.dart';
import 'package:shelf_router/shelf_router.dart';

const maxFileBytes = 5 * 1024 * 1024; // 5 MB per file
const maxRequestBytes = 6 * 1024 * 1024; // whole request body
const allowedTypes = {'image/png', 'image/jpeg', 'image/gif', 'application/pdf'};

final uploadDir = Directory('uploads');
final _random = Random.secure();

class UploadException implements Exception {
  final int status;
  final String message;
  UploadException(this.status, this.message);
}

const uploadForm = '''
<!doctype html>
<form method="post" action="/upload" enctype="multipart/form-data">
  <input name="title">
  <input type="file" name="files" multiple>
  <button>Upload</button>
</form>
''';

String randomName() =>
    List.generate(16, (_) => _random.nextInt(256).toRadixString(16).padLeft(2, '0')).join();

/// Writes [data] to [file], failing as soon as it exceeds [maxBytes].
Future<int> saveWithLimit(Stream<List<int>> data, File file, int maxBytes) async {
  final sink = file.openWrite();
  var total = 0;
  try {
    await for (final chunk in data) {
      total += chunk.length;
      if (total > maxBytes) {
        throw UploadException(413, 'file larger than $maxBytes bytes');
      }
      sink.add(chunk);
    }
  } finally {
    await sink.close();
  }
  return total;
}

/// Detects the real type from the first bytes of the file.
Future<String?> sniffType(File file) async {
  final header = await file
      .openRead(0, defaultMagicNumbersMaxLength)
      .expand((chunk) => chunk)
      .toList();
  return lookupMimeType('', headerBytes: header);
}

Future<Map<String, Object>> saveFile(FormData formData) async {
  final tmp = File('${uploadDir.path}/${randomName()}.part');
  try {
    final size = await saveWithLimit(formData.part, tmp, maxFileBytes);
    final type = await sniffType(tmp);
    if (type == null || !allowedTypes.contains(type)) {
      throw UploadException(415, 'type ${type ?? 'unknown'} not allowed');
    }
    final ext = extensionFromMime(type);
    final saved = await tmp.rename('${uploadDir.path}/${randomName()}.$ext');
    return {
      'originalName': formData.filename!,
      'declaredType': formData.part.headers['content-type'] ?? '',
      'detectedType': type,
      'size': size,
      'savedAs': saved.uri.pathSegments.last,
    };
  } catch (_) {
    if (await tmp.exists()) await tmp.delete();
    rethrow;
  }
}

Future<Response> upload(Request request) async {
  final form = request.formData();
  if (form == null) {
    return Response.badRequest(body: 'expected multipart/form-data\n');
  }
  final length = request.contentLength;
  if (length != null && length > maxRequestBytes) {
    return Response(413, body: 'request too large\n');
  }

  final fields = <String, String>{};
  final files = <Map<String, Object>>[];
  try {
    await for (final formData in form.formData) {
      if (formData.filename == null) {
        fields[formData.name] = await formData.part.readString();
      } else if (formData.filename!.isNotEmpty) {
        files.add(await saveFile(formData));
      }
    }
  } on UploadException catch (e) {
    return Response(e.status, body: '${e.message}\n');
  }

  return Response.ok(
    '${const JsonEncoder.withIndent('  ').convert({'fields': fields, 'files': files})}\n',
    headers: {'content-type': 'application/json'},
  );
}

Future<void> main() async {
  await uploadDir.create();
  final router = Router()
    ..get('/', (Request _) => Response.ok(uploadForm, headers: {'content-type': 'text/html'}))
    ..post('/upload', upload);

  final port = int.parse(Platform.environment['PORT'] ?? '8080');
  final server = await io.serve(router.call, 'localhost', port);
  print('Serving at http://${server.address.host}:${server.port}');
}

curl -F sends multipart/form-data, exactly like a browser form. -F name=value adds a field, -F name=@file adds a file, and ;filename= overrides the file name that is sent:

$ curl -F title=Receipts -F files=@cat.png -F "files=@invoice.pdf;filename=2026 invoice.pdf" http://localhost:8080/upload
{
  "fields": {
    "title": "Receipts"
  },
  "files": [
    {
      "originalName": "cat.png",
      "declaredType": "image/png",
      "detectedType": "image/png",
      "size": 73,
      "savedAs": "5ac397e6597e3e178a81d110bf104a31.png"
    },
    {
      "originalName": "2026 invoice.pdf",
      "declaredType": "application/pdf",
      "detectedType": "application/pdf",
      "size": 2009,
      "savedAs": "a866743c97d60b55725395f85a5031fd.pdf"
    }
  ]
}

A text file renamed to .png, a file over the limit, and a request that isn't multipart:

$ printf '<html><script>alert(1)</script></html>' > fake.png
$ curl -i -F files=@fake.png http://localhost:8080/upload
HTTP/1.1 415 Unsupported Media Type
...
type unknown not allowed

$ curl -F files=@huge.pdf http://localhost:8080/upload
file larger than 5242880 bytes

$ curl -i -d x=1 http://localhost:8080/upload
HTTP/1.1 400 Bad Request
...
expected multipart/form-data

curl reported fake.png as image/png based on the extension, but the first bytes aren't a PNG signature, so the server rejected it. In both error cases the partially written .part file was deleted.

Notes on the design:

Safe file names

Sometimes you do want the original name, for showing it in a list or when the file is downloaded again. The client controls it completely, so clean it before use, and still never use it to build a path:

import 'package:path/path.dart' as p;

/// Turns a client-supplied file name into something safe to display
/// or to use in a Content-Disposition header. Never use it as a path.
String safeFilename(String name) {
  // Browsers on Windows may send "C:\fakepath\x.png"; treat \ as a separator too.
  var base = p.posix.basename(name.replaceAll(r'\', '/'));
  base = base
      .replaceAll(RegExp(r'[\x00-\x1f\x7f"<>:|?*]'), '_') // control and reserved chars
      .replaceAll(RegExp(r'^[.\s]+|[.\s]+$'), ''); // leading dots, trailing dots/spaces
  if (base.length > 100) {
    final ext = p.extension(base);
    base = base.substring(0, 100 - ext.length) + ext;
  }
  return base.isEmpty ? 'file' : base;
}

void main() {
  for (final name in [
    'holiday.jpg',
    '../../etc/passwd',
    r'C:\fakepath\report.pdf',
    '.htaccess',
    'name"with<odd>chars?.txt',
    'zdjęcie kota.png',
    '...',
    'a' * 120 + '.png',
  ]) {
    final shown = name.length > 30 ? '${name.substring(0, 27)}...' : name;
    print('${shown.padRight(32)}${safeFilename(name)}');
  }
}

Output:

holiday.jpg                     holiday.jpg
../../etc/passwd                passwd
C:\fakepath\report.pdf          report.pdf
.htaccess                       htaccess
name"with<odd>chars?.txt        name_with_odd_chars_.txt
zdjęcie kota.png                zdjęcie kota.png
...                             file
aaaaaaaaaaaaaaaaaaaaaaaaaaa...  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.png

Non-ASCII names survive. package:http and browsers send them as raw UTF-8 bytes in the part header, and package:mime (and therefore shelf_multipart) decodes headers as UTF-8. A client that sends the name in another encoding makes the parser throw a FormatException, which Shelf turns into a 500 response. Catch it if you want a 400 instead.

Upload progress

MultipartFile accepts any stream, so wrap the file stream in one that counts the bytes as they are read:

import 'dart:io';

import 'package:http/http.dart' as http;

/// Creates a MultipartFile that reports progress while it is being read.
Future<http.MultipartFile> fileWithProgress(
  String field,
  String path, {
  String? filename,
  required void Function(int sent, int total) onProgress,
}) async {
  final file = File(path);
  final total = await file.length();
  var sent = 0;
  final stream = file.openRead().map((chunk) {
    sent += chunk.length;
    onProgress(sent, total);
    return chunk;
  });
  return http.MultipartFile(field, stream, total,
      filename: filename ?? file.uri.pathSegments.last);
}

Future<void> main(List<String> args) async {
  final url = Uri.parse(args[0]);
  var lastPercent = -1;
  final request = http.MultipartRequest('POST', url)
    ..files.add(await fileWithProgress(
      'files',
      args[1],
      filename: args.length > 2 ? args[2] : null,
      onProgress: (sent, total) {
        final percent = sent * 100 ~/ total;
        if (percent ~/ 25 != lastPercent ~/ 25) {
          print('uploaded $sent of $total bytes ($percent%)');
        }
        lastPercent = percent;
      },
    ));

  final response = await http.Response.fromStream(await request.send());
  print('${response.statusCode}: ${response.body}');
}

Uploading a 4 MB PNG to the Shelf server above, under a Polish file name:

$ dart run progress.dart http://localhost:8080/upload big.png "zdjęcie kota.png"
uploaded 1114112 of 4194377 bytes (26%)
uploaded 2162688 of 4194377 bytes (51%)
uploaded 3211264 of 4194377 bytes (76%)
uploaded 4194377 of 4194377 bytes (100%)
200: {
  "fields": {},
  "files": [
    {
      "originalName": "zdjęcie kota.png",
      "declaredType": "application/octet-stream",
      "detectedType": "image/png",
      "size": 4194377,
      "savedAs": "c2b4122d255262ac611cc0de58baf73a.png"
    }
  ]
}

No contentType was passed, so the part was declared as application/octet-stream. The server didn't care because it checks the content.

The counter measures bytes handed to the socket, not bytes the server received, so 100% shows up a moment before the server finishes. On a fast connection that's a few socket buffers. When the server responds, the upload is done. In Flutter, call setState (or update a ValueNotifier) from onProgress to drive a LinearProgressIndicator.

Raw body uploads

When there's one file and no form fields, sending the file as the whole request body is simpler and avoids the multipart overhead. This is how you upload to S3 presigned URLs, Google Cloud Storage, and many APIs.

On the client, http.StreamedRequest streams the body from a file. On the server, request.read() is the body as a byte stream:

import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

final storage = Directory('uploads');

Future<Response> putFile(Request request, String id) async {
  if (!RegExp(r'^[a-z0-9-]{1,64}$').hasMatch(id)) {
    return Response.badRequest(body: 'bad id');
  }
  final file = File('${storage.path}/$id.bin');
  final sink = file.openWrite();
  await sink.addStream(request.read());
  await sink.close();
  return Response(201, body: 'stored ${await file.length()} bytes as $id');
}

Future<void> main() async {
  await storage.create();
  final router = Router()..put('/files/<id>', putFile);
  final server = await io.serve(router.call, 'localhost', 0);

  // Client: stream a file as the raw request body.
  final source = File('report.pdf');
  final request = http.StreamedRequest(
    'PUT',
    Uri.parse('http://localhost:${server.port}/files/q3-report'),
  )
    ..headers['content-type'] = 'application/pdf'
    ..contentLength = await source.length();

  final responseFuture = request.send(); // start sending...
  await request.sink.addStream(source.openRead()); // ...feed the body...
  await request.sink.close(); // ...and finish it
  final response = await http.Response.fromStream(await responseFuture);
  print('${response.statusCode} ${response.body}');

  // Small payloads don't need streaming:
  final small = await http.put(
    Uri.parse('http://localhost:${server.port}/files/greeting'),
    body: 'hello',
  );
  print('${small.statusCode} ${small.body}');

  await server.close();
}

Output:

201 stored 3145728 bytes as q3-report
201 stored 5 bytes as greeting

Things to note:

Serving uploaded files

When you send an uploaded file back to users:

String contentDisposition(String filename) {
  // ASCII-only fallback for old clients, plus the RFC 5987 UTF-8 version.
  final fallback = filename.replaceAll(RegExp(r'[^\x20-\x7e]|["\\]'), '_');
  final encoded = Uri.encodeComponent(filename);
  return "attachment; filename=\"$fallback\"; filename*=UTF-8''$encoded";
}

void main() {
  print(contentDisposition('report.pdf'));
  print(contentDisposition('zdjęcie kota.png'));
}

Output:

attachment; filename="report.pdf"; filename*=UTF-8''report.pdf
attachment; filename="zdj_cie kota.png"; filename*=UTF-8''zdj%C4%99cie%20kota.png

Summary

Task How
Upload files + fields (client) http.MultipartRequest, fields[...], files.add(MultipartFile.fromPath(...))
File from memory MultipartFile.fromBytes(field, bytes, filename: ...)
Set the part's type contentType: MediaType('image', 'png') from package:http_parser
Upload progress MultipartFile(field, countingStream, length)
Raw body upload (client) http.StreamedRequest with contentLength, or http.put(url, body: bytes)
Parse multipart with dart:io MimeMultipartTransformer(boundary).bind(request) from package:mime
Parse form data with Shelf request.formData() from package:shelf_multipart
Detect the real type lookupMimeType('', headerBytes: firstBytes)
Pick a safe extension extensionFromMime(detectedType)
Limit size count bytes while streaming, delete the partial file on failure

Rules worth remembering: stream files instead of buffering them, enforce size limits in the streaming loop, check the content instead of trusting the name or declared type, store files under names you generate, and treat the original file name as display text only.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents