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

9

我希望将一张图片以multipart文件的形式发送到服务器。

首先,我尝试使用http.post

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

我遇到了这个错误:

无效状态:不能使用内容类型“multipart/form-data”设置请求的正文字段。

查看这个主题的答案后,我尝试使用dio package

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 可用时受支持。

已经有一个问题在这里 开启 了。

最后,我尝试使用 http 包 中的 MultipartRequest

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包时完全相同的错误。

如果有人有解决方案,我会非常乐意接受。

1个回答

17

使用 http 包,使用 fromBytes 而不是 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();

谢谢您的回答,顺便问一下这部分代码的作用是什么:contentType: MediaType.parse(mimeType),它在哪里定义的?另外,我尝试了不加这部分代码也可以正常工作。 - JS1
1
这只是来自任何文件的元数据。你不需要它。 - Rubens Melo
1
在这个方法中,您在哪里添加字段名称?在问题的上下文中,“fichier”是我所指的。 - letsintegreat
请查看 https://dev59.com/WdX8oIgBc1ULPQZFDW6L,上传后我需要在 Future<String> 中返回响应体。 - MrSalesi
@RubensMelo 如果我在令牌过期后刷新令牌并尝试调用此请求,会出现错误,即同一请求不能发送两次。有解决办法吗? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接