Uploading Files
Files are often uploaded as part of a multipart form request. A request of this type has the content-type multipart/form-data and is body is made up of multiple data parts. These segments are typically the base64 encoded contents of a file and accompanying metadata for the upload.
Multipart data is decoded using objects from package:mime. You must add this package your application's pubspec.yaml file:
1
dependencies:
2
mime: any # prefer a better constraint than this
Copied!
By default, resource controllers only accept application/json requests and must be configured to accept multipart/form-data requests. To read each part, create a MimeMultipartTransformer and stream the body into it. The following shows an example:
1
import 'package:conduit/conduit.dart';
2
import 'package:mime/mime.dart';
3
4
class MyController extends ResourceController {
5
MyController() {
6
acceptedContentTypes = [ContentType("multipart", "form-data")];
7
}
8
9
@Operation.post()
10
Future<Response> postForm() async {}
11
final boundary = request.raw.headers.contentType.parameters["boundary"];
12
final transformer = MimeMultipartTransformer(boundary);
13
final bodyBytes = await request.body.decode<List<int>>();
14
15
// Pay special attention to the square brackets in the argument:
16
final bodyStream = Stream.fromIterable([bodyBytes]);
17
final parts = await transformer.bind(bodyStream).toList();
18
19
for (var part in parts) {
20
final headers = part.headers;
21
final content = await part.toList();
22
23
// Use headers['content-disposition'] to identify the part
24
// The byte content of the part is available in 'content'.
25
}
26
}
27
}
Copied!
Copy link