使用 MultipartFile 将 XFile 图像发送到 API - Flutter

问题描述 投票:0回答:2

我有一个适用于网络、Android 和 ios 的应用程序。 我已经实现了下面的包

https://pub.dev/packages/image_picker/example

  • 图像选择器:^0.8.2
  • image_picker_for_web:^2.1.1

任务:

  1. 用户需要选择多个图像(通过 android 进行调试时,我有时会收到 websocket 连接期望,并且应用程序退出时没有任何错误消息。如果您也能够对此问题提供一些见解,那就太好了)

  2. 点击提交将图像(XFile)上传到API

class UserAttachments {
  List<XFile>? attachments = [];
  int userID = 0;
}

Future<String> submitImage(UserAttachments ua) async {
  http.MultipartRequest request =
      new http.MultipartRequest("POST", Uri.parse(kAttachmentsURI));

  Map<String, String> headers = {"Content-Type": "application/json"};

  ua.attachments!.forEach((element) async {
    var bytes = element.readAsBytes();
    request.files.add(new http.MultipartFile.fromBytes('file', await bytes));
  });

  request.headers.addAll(headers);
  request.fields['userID'] = '23';

  http.StreamedResponse responseAttachmentSTR = await request.send();

  print(responseAttachmentSTR.statusCode);
  return "SENT"; // + "  - Respomse:  " + map.toString();
}

上面的代码似乎不起作用。有适合 web/android/ios 的解决方案吗?

android react-native flutter dart multipartform-data
2个回答
0
投票

您不能在 forEach 上使用 async,因为这只会返回一个 Promise 数组,而不会等待它们。要解决此问题,您可以使用

for loop
来实现异步函数。

for(var i = 0; i < ua.attachments!.length; i++) {
  var element = ua.attachments[i];
  var bytes = element.readAsBytes();
  request.files.add(new http.MultipartFile.fromBytes('file', await bytes));
}

您可以使用

Future.wait

优化此代码
Future<String> submitImage(UserAttachments ua) async {
      http.MultipartRequest request =
          new http.MultipartRequest("POST", Uri.parse(kAttachmentsURI));
    
      Map<String, String> headers = {"Content-Type": "application/json"};
    
      var bytes = await Future.wait(ua.attachments!.map((el) => el.readAsBytes()));
      request.files.addAll(bytes.map((b) => new http.MultipartFile.fromBytes('file', b)));
    
      request.headers.addAll(headers);
      request.fields['userID'] = '23';
    
      http.StreamedResponse responseAttachmentSTR = await request.send();
    
      print(responseAttachmentSTR.statusCode);
      return "SENT";
}

0
投票
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';

Future<void> uploadXFile(XFile xfile) async {
  Dio dio = Dio();
  String url = 'https://example.com/upload'; // Replace with your API endpoint

  try {
    // Convert XFile to MultipartFile
    MultipartFile multipartFile = await MultipartFile.fromFile(
      xfile.path,
      filename: xfile.name, // Optional: Custom file name
    );

    // Create FormData
    FormData formData = FormData.fromMap({
      'file': multipartFile,
    });

    // Send POST request
    Response response = await dio.post(
      url,
      data: formData,
      options: Options(
        headers: {
          "Content-Type": "multipart/form-data", // Required header
        },
      ),
    );

    print("Response: ${response.data}");
  } catch (e) {
    print("Upload failed: $e");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.