使用browser_client.dart进行多部分请求

时间:2017-11-04 16:56:31

标签: dart multipartform-data angular-dart

我正在尝试使用BrowserClient (package:http/browser_client.dart)发送多部分请求。我找到了答案:firstsecond。但他们都使用HttpRequest。 BrowserClient可以发布字符串,列表或地图,但我想我应该发送html.FormData。

1 个答案:

答案 0 :(得分:3)

感谢@filiph,我发现我们如何从angularDart客户端发送带有文件的多部分请求,可能对某人有用。例如,我们有简单的角度飞镖模板:

<input #fileInput type="file" accept="image/*" name="file">

这是文件上传的简单组件:

class FileComponent implements AfterViewInit {

  final Client _http;

  @ViewChild("fileInput")
  ElementRef cameraInputRef;

  HealthApiImpl(this._http);

  @override
  ngAfterViewInit() {
    FileUploadInputElement uploadInput = cameraInputRef.nativeElement;
    uploadInput.onChange.listen((e) {
      File file = (e.target as dynamic).files[0];
      createMultipartFileAndUpload(file);
    });
  }

  void createMultipartFileAndUpload(File file) {
    FileReader fileReader = new FileReader();
    fileReader.onLoad.listen((e) {
      var target = e.target as dynamic;
      List<int> result = target.result;
      MultipartFile mf = new MultipartFile.fromBytes(
          "file",
          result,
          filename: file.name,
          contentType: new MediaType.parse(file.type));
      upload(mf);
    });
    fileReader.readAsArrayBuffer(file);
  }

  void upload(MultipartFile file) {
    var uri = Uri.parse("/uploadUrl");
    var request = new MultipartRequest("POST", uri);
    request.files.add(file);
    var response = await _http.send(request);
    if (response.statusCode == 200) {
        print("success upload");
    }
    throw new "upload error";
  }
}

客户端被注入角色飞镖游的英雄示例。