如何使用 Flutter 发送多部分文件

2024-01-01

我想将图片作为多部分文件发送到服务器。

首先我尝试使用http.post :

var response = await http.post(
      Uri.parse('url.php'),
      headers:{ "Content-Type":"multipart/form-data" } ,
      body: {
        "fichier": base64img
      }
    );

我收到这个错误:

错误状态:无法设置具有内容类型的请求的正文字段 “多部分/表单数据”。

看着大家的回答这个话题 https://stackoverflow.com/questions/49125191/how-to-upload-images-and-file-to-a-server-in-flutter我尝试使用迪奥封装 :

var dio = Dio();
    var formData = FormData.fromMap({
      'fichier': await MultipartFile.fromFile(filePath, filename: 'upload')
    });
    var response = await dio.post(
      'url.php', 
      data: formData
    );

我收到这个错误:

错误:不支持的操作:仅在以下情况下支持 MultipartFile dart:io 可用。

一个已经开放的问题here https://github.com/flutterchina/dio/issues/1067.

最后,我尝试使用多部分请求来自http包 :

var url = Uri.parse('url.php');
    var request = new http.MultipartRequest("POST", url);
    request.files.add(
      await http.MultipartFile.fromPath(
        "fichier", 
        filePath
      )
    );
    request.send().then((response) => print(response));

得到与 dio 包完全相同的错误。

如果有人作为解决方案,我很乐意接受。


使用http包并使用获取图像fromBytes intead fromPath:

final uri = Uri.parse('https://myendpoint.com');
var request = new http.MultipartRequest('POST', uri);
final httpImage = http.MultipartFile.fromBytes('files.myimage', bytes,
    contentType: MediaType.parse(mimeType), filename: 'myImage.png');
request.files.add(httpImage);
final response = await request.send();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Flutter 发送多部分文件 的相关文章