使用MultiPartRequest上传多张图片:内容大小低于指定的contentLength

时间:2019-10-29 13:57:05

标签: flutter dart

我正在尝试将多个图像上传到服务器。我正在使用http.MultipartRequest。

发现主要错误

未处理的异常:内容大小小于指定的contentLength。已写入76个字节,但预期为130707。

错误

E/flutter (12577): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Content size below specified contentLength.  76 bytes written but expected 130707.
E/flutter (12577): #0      IOClient.send (package:http/src/io_client.dart:65:7)
E/flutter (12577): <asynchronous suspension>
E/flutter (12577): #1      BaseRequest.send (package:http/src/base_request.dart:116:35)
E/flutter (12577): <asynchronous suspension>
E/flutter (12577): #2      CreateCarDS.uploadImage (package:usedcars_flutter/data_service/create_car_ds.dart:141:34)
E/flutter (12577): #3      _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:43:6)
E/flutter (12577): #4      CreateCarDS.uploadImage (package:usedcars_flutter/data_service/create_car_ds.dart:115:44)
E/flutter (12577): #5      AddPageState._editCarNetwork.<anonymous closure>.<anonymous closure> (package:usedcars_flutter/screens/tabs/add_page.dart:1042:36)
E/flutter (12577): #6      State.setState (package:flutter/src/widgets/framework.dart:1141:30)
E/flutter (12577): #7      AddPageState._editCarNetwork.<anonymous closure> (package:usedcars_flutter/screens/tabs/add_page.dart:997:13)
E/flutter (12577): #8      _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (12577): #9      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (12577): #10     _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter (12577): #11     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter (12577): #12     Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter (12577): #13     Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter (12577): #14     _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
E/flutter (12577): #15     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
E/flutter (12577): #16     CreateCarDS.editCar (package:usedcars_flutter/data_service/create_car_ds.dart)
E/flutter (12577): #17     _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
E/flutter (12577): #18     _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (12577): #19     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (12577): #20     _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter (12577): #21     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter (12577): #22     Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter (12577): #23     Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter (12577): #24     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:552:7)
E/flutter (12577): #25     _rootRun (dart:async/zone.dart:1124:13)
E/flutter (12577): #26     _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (12577): #27     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter (12577): #28     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter (12577): #29     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (12577): #30     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
E/flutter (12577): 

上传功能

在此功能中,我得到的图像为List<File>。我遍历图像列表,并将每个multipartFile添加到request.files。我想在这里我错过了一些代码。

Future<http.StreamedResponse> uploadImages({
    int id,
    List<File> images,
  }) async {

    String apiUrl = CAR_IMAGE_ADD_URL + id.toString() + '/';
    debugPrint(apiUrl);

    var uri = Uri.parse(apiUrl);
    var request = new http.MultipartRequest('POST', uri);
    request.headers.addAll({'Authorization': 'Bearer ' + Profile.instance.accessToken, 'Content-Type': 'multipart/form-data'});

    images.forEach((image) async {
      var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
      final length = await image.length();
      var multipartFile = new http.MultipartFile('image', stream, length,
          filename: basename(image.path));
      request.files.add(multipartFile);
    });

    var response = await request.send();
    print(response.statusCode);
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });
    uploadStatusCode = httpStatusCodeFinder(response.statusCode);
    print(response);
    return response;
  }
  1. 我的语法正确吗?
  2. 我可以使用上述方法上传多张图像吗?

如果您有任何建议或答案,那将非常有帮助。

3 个答案:

答案 0 :(得分:1)

我建议您使用dio。 这是一个更好,更强大的http客户端。

https://pub.dev/packages/dio

您可以轻松上传多部分文件,并另外接收上传进度。 此外,您可以创建一个包含静态Dio的httpservice,它将一次创建并由getter访问。因此,您只需要在初始化时放置一次授权或将拦截器设置为客户端即可。

答案 1 :(得分:1)

否,您要引入一个细微的错误。通过制作forEach闭包async,它会自动返回一个future-不会内联执行。

迭代列表时,优选for胜过forEach

  var request = http.MultipartRequest('POST', Uri.parse(apiUrl));
  request.headers.addAll({
    'Authorization': 'Bearer ' + Profile.instance.accessToken,
    'Content-Type': 'multipart/form-data'
  });

  for (var image in images) {
    var stream = http.ByteStream(DelegatingStream.typed(image.openRead()));
    final length = await image.length();
    request.files.add(http.MultipartFile(
      'image', // consider using a unique name per image here
      stream,
      length,
      filename: basename(image.path),
    ));
  }

答案 2 :(得分:0)

就我而言,我的照片是 Uint8List,在请求之前我想创建一个文件。

我的问题是缺少 write 函数的等待。

await file.writeAsBytes(photo);

可能是函数没有写完,触发了请求。