【问题标题】:Image Upload with flutter http MultipartFile使用flutter http MultipartFile上传图片
【发布时间】:2021-11-28 04:33:50
【问题描述】:

现在我正在使用 http 包创建一个使用 Flutter 上传图像的功能

这是上传图片到服务器的代码

Future<String> uploadNewImage(String imagePath) async {
  var postUri = Uri.parse("https://test.vahupu.com/g2.php?mode=fileupload");
  var request = http.MultipartRequest("POST", postUri);
  request.files.add(
    await http.MultipartFile.fromPath(
      "file",
      imagePath,
      filename: imagePath.split("/").last,
    ),
  );
  var response = await request.send();
  if (response.statusCode == 200) {
    var responseString = await response.stream.bytesToString();
    var responseJson = json.decode(responseString);
    if (responseJson.isEmpty) {
      showErrorDialog("Server Error");
      return "";
    } else {
      showErrorDialog("Image Uploaded Succesfully");
      return responseJson["filepath"];
    }
  } else {
    showErrorDialog("Something Went Wrong");
  }
  return "";
}

imagePath来自image_picker包

Future _getImgFromGallery() async {
  XFile? image = await picker.pickImage(
    source: ImageSource.gallery,
    imageQuality: 50,
  );
  if (image != null) {
    String imageName = await uploadNewImage(
      image.path,
    );
    if (imageName != "") {
      widget.addOrRemoveImage(imageNameList, image.path);
    }
  }
}

此 api 端点与我的 Thunderclient (用于 POSTMAN 的替代方案)配合得很好。

但是代码对flutter应用不起作用,API返回一个空响应。

【问题讨论】:

    标签: flutter http dart


    【解决方案1】:

    我终于找到了解决方案...

    在服务器端 api 中使用 php 中的$_FILES["file"]["type"] 操作验证文档

    但 http.MultipartFile 函数使用application/octet-stream 发送数据

    所以 if 条件没有在服务器端执行。所以 api 返回一个空的响应。

    content-type: MediaType.parse("image/png") 我在 http.MultipartFile 函数中添加了这行代码。所以我解决了这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2019-11-22
      • 2020-12-27
      • 2020-07-08
      • 2019-02-03
      相关资源
      最近更新 更多