【问题标题】:Flutter Image upload issueFlutter 图片上传问题
【发布时间】:2019-02-03 22:07:39
【问题描述】:

我正在尝试使用以下功能上传图片,一切正常,只是我想在帖子中发送图片,而当我尝试让图片一无所获时

这是调用 API

Future getUploadImg(access_token,File _image) async {
  print("Image: $_image");
  String apiUrl = '$_apiUrl/user/upload-profile-image';
  final length = await _image.length();
  final request = new http.MultipartRequest('POST', Uri.parse(apiUrl));
  request.headers['Accesstoken'] = "Bearer $access_token";
  request.files.add(new http.MultipartFile('imagefile',_image.openRead(), length));

  http.Response response = await http.Response.fromStream(await request.send());
  print("Result: ${response.body}");
  return json.decode(response.body);
}

我传递给服务器的文件是:

File: '/storage/emulated/0/Android/data/com.dotsquares.ecomhybrid/files/Pictures/c5df03f7-097d-47ca-a3c5-f896b2a38c086982492957343724084.jpg'

【问题讨论】:

  • 您能解释一下您面临的问题吗?
  • 当我使用 API 参数传递图像时,没有进入 POST 或 File 方法。

标签: php image api flutter image-uploading


【解决方案1】:

我终于得到了结果,如果有人需要帮助,我们需要传递图像共享我的工作代码的字符串:

Future getUploadImg(access_token,File _image) async {
  print("Image: $_image");
  var result;
  var stream = new http.ByteStream(DelegatingStream.typed(_image.openRead()));
  var length = await _image.length();
  var uri = Uri.parse('$_apiUrl/user/upload-profile-image');
  var request = new http.MultipartRequest("POST", uri);
  request.headers['Accesstoken'] = "Bearer $access_token";
  var multipartFile = new http.MultipartFile('imagefile', stream, length, filename: basename(_image.path));
  request.files.add(multipartFile);
  var response = await request.send();

  print(" ===================response code ${response.statusCode}");
  await response.stream.transform(utf8.decoder).listen((value) {
    print(" =====================response value $value");
    result = value;
  });
  return json.decode(result);

}

【讨论】:

  • 我使用了上面相同的代码,不幸的是我遇到了错误,有什么线索吗?谢谢! {"error":{"name":"MulterError","message":"Unexpected field","code":"LIMIT_UNEXPECTED_FILE","field":"property","storageErrors":[]}}
【解决方案2】:

为了避免以下问题:

  • 写入失败
  • 连接在...之前关闭
  • Flutter Doctor 错误 - SocketException:写入失败(操作系统错误:管道损坏,errno = 32)

您需要在标题中添加正确的参数。

就我而言,这些问题发生在上传图片和发送 base64 编码请求时。我通过添加以下“连接”标头解决了它:“保持活动”:

  final response = await this.httpClient.put(
    url,
    encoding: Utf8Codec(),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
      'Accept': "*/*",
      'connection': 'keep-alive',
      'Accept-Encoding' : 'gzip, deflate, br',
    },
    body: body,
  );

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2021-10-18
    • 2011-04-23
    • 2020-07-08
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多