【问题标题】:Uploading file using POST request in Flutter在 Flutter 中使用 POST 请求上传文件
【发布时间】:2018-06-08 12:39:02
【问题描述】:

我正在尝试使用发布请求将视频文件上传到我的服务器。

var file = new File(videoPath);
var uri = Uri.parse(tokenizedUri);
HttpClientRequest request = await new HttpClient().postUrl(uri);

await request.addStream(file.openRead());
var response = await request.close();

response.transform(utf8.decoder).forEach((string) {
  print(string); // handle data
});

但是服务器没有得到它。为什么?

【问题讨论】:

  • 问题是什么?

标签: flutter


【解决方案1】:

正确的方法是使用MultipartRequest:

    var uri = Uri.parse(url);
    var request = new MultipartRequest("POST", uri);

    var multipartFile = await MultipartFile.fromPath("package", videoPath);
    request.files.add(multipartFile);

    StreamedResponse response = await request.send();
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });

【讨论】:

  • 嗨,我正在做同样的事情,但没有在服务器中获取文件。这是我的代码request.fields['title'] = title.text; request.fields['sub_title'] = subTitle.text; var profile_photo = await MultipartFile.fromPath("profile_photo", photo.path); request.files.add(profile_photo); request.files .add(await http.MultipartFile.fromPath('profile_video', video.path)); var response = await request.send(); var responseString = await response.stream.bytesToString(); print(responseString); {sub_title":"dd","profile_photo":{},"profile_video":{}}
【解决方案2】:

您可以使用Dio 包。它支持大文件,对我来说很好用。

sendFile(String kMainUrl, XFile file) async {
    String filePath = file.path;
    String fileName = 'any name';

    try {
      FormData formData = FormData.fromMap({
        "file":
        await MultipartFile.fromFile(filePath, filename:fileName),
      });
      Response response =
      await Dio().post(kMainUrl, data: formData);
      print("File upload response: $response");
      print(response.data['message']);
    } catch (e) {
      print("Exception Caught: $e");
    }
}

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 2018-12-16
    • 2021-08-10
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多