如何将上传的多部分文件写入磁盘?

时间:2019-03-03 02:25:37

标签: dart aqueduct

我正在尝试使用Aqueduct通过多部分请求处理文件上传。渡槽现在在此处提供了有关如何处理多部分请求的示例:

https://aqueduct.io/docs/http/request_and_response/#example-multipartform-data

该示例说明了如何获取文件的标题和内容。但是,它没有说明如何将内容写入磁盘上的文件中。

如何写入上传到磁盘的文件内容?

下面的示例显示了我想要实现的目标,但不起作用:

import 'dart:io';

import 'package:aqueduct/aqueduct.dart';
import 'package:mime/mime.dart';

class MediaUploadController extends ResourceController {
  MediaUploadController() {
    acceptedContentTypes = [ContentType("multipart", "form-data")];
  }

  @Operation.post()
  Future<Response> postMultipartForm() async {
    final transformer = MimeMultipartTransformer(request.raw.headers.contentType.parameters["boundary"]);
    final bodyStream = Stream.fromIterable([await request.body.decode<List<int>>()]);
    final parts = await transformer.bind(bodyStream).toList();

    for (var part in parts) {
      final String contentType = part.headers["content-type"];

      // Write content to disk
      final content = await part.toList();

      final fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".jpg";
      var file = new File('data/' + fileName);
      var sink = file.openWrite();
      sink.write(content);
      sink.close();
    }

    return new Response.ok({});   
  }
}

1 个答案:

答案 0 :(得分:1)

这在下面确实有效。除了mime包之外,我还向pubspec.yaml中添加了http_server包,因为它使处理多部分表单数据更容易。

dependencies:
  aqueduct: ^3.0.1
  mime: ^0.9.6+2
  http_server: ^0.9.8+1

然后,我研究了其他一些框架,以了解它们如何处理写入文件。要获得这些多部分的内容和流如何协同工作是如此复杂。但是终于在将近一个星期之后,隧道尽头的光...直到下一个问题出现。最有可能在10分钟内到达:)

import 'dart:io';

import 'package:aqueduct/aqueduct.dart';
import 'package:mime/mime.dart';
import 'package:http_server/http_server.dart';

class MediaUploadController extends ResourceController {
  MediaUploadController() {
    acceptedContentTypes = [ContentType("multipart", "form-data")];
  }

  @Operation.post()
  Future<Response> postMultipartForm() async {
    final transformer = MimeMultipartTransformer(request.raw.headers.contentType.parameters["boundary"]);
    final bodyStream = Stream.fromIterable([await request.body.decode<List<int>>()]);
    final parts = await transformer.bind(bodyStream).toList();

    for (var part in parts) {
      HttpMultipartFormData multipart = HttpMultipartFormData.parse(part);

      final ContentType contentType = multipart.contentType;

      final content = multipart.cast<List<int>>();

      final filePath = "data/" + DateTime.now().millisecondsSinceEpoch.toString() + ".jpg";

      IOSink sink = File(filePath).openWrite();
      await for (List<int> item in content) {
        sink.add(item);
      }
      await sink.flush();
      await sink.close();
    }

    return new Response.ok({});   
  }
}