How to send multipart HTTP requests from browser with Dart

半腔热情 提交于 2019-12-11 03:43:10

问题


I have to upload an image from browser to my RESTful web API, implemented using Python Eve. From documentation, It requires sending multipart/data-form request. (http://python-eve.org/features.html#file-storage). There is 'dart:http' library that could do. But, it requires 'dart:io', which is not available on browser. So, is there anyway I can send the request from browser?

Thank you for any help.


回答1:


You can just use something like this:

FormData formData = new FormData();
formData.append('image', '...');
HttpRequest.request('url', method: 'post', sendData: formData).then((HttpRequest request) {
  // ...
});

This should set the correct mimeType. If not you can set it with the mimeType parameter.

Regards, Robert




回答2:


Client side, the dart:html library should do the trick. Something like this (source):

import 'dart:html';

main() {
  InputElement uploadInput = query('#upload');
  uploadInput.on.change.add((e) {
    // read file content as dataURL
    final files = uploadInput.files;
    if (files.length == 1) {
      final file = files[0];
      final reader = new FileReader();
      reader.on.load.add((e) {
        sendDatas(reader.result);
      });
      reader.readAsDataURL(file);
    }
  });
}

/// send data to server
sendDatas(dynamic data) {
  final req = new HttpRequest();
  req.on.readyStateChange.add((Event e) {
    if (req.readyState == HttpRequest.DONE &&
        (req.status == 200 || req.status == 0)) {
      window.alert("upload complete");
    }
  });
  req.open("POST", "http://127.0.0.1:8080/upload");
  req.send(data);
}


来源:https://stackoverflow.com/questions/25025084/how-to-send-multipart-http-requests-from-browser-with-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!