简体   繁体   English

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

[英]Multiple image upload using MultiPartRequest: Content size below specified contentLength

I am trying to upload multiple images to the server.我正在尝试将多个图像上传到服务器。 I am using http.MultipartRequest.我正在使用 http.MultipartRequest。

Main Error Noticed发现主要错误

Unhandled Exception: Content size below specified contentLength.未处理的异常:内容大小低于指定的 contentLength。 76 bytes written but expected 130707.已写入 76 个字节,但预期为 130707。

Error错误

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): 

UPLOAD FUNCTION上传 FUNCTION

In this function, I get images as List<File> .在这个 function 中,我将图像作为List<File> I looped through the images List, and added each multipartFile to request.files.我遍历图像列表,并将每个 multipartFile 添加到 request.files。 I think here I missed some code.我想在这里我错过了一些代码。

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. Is my syntax correct?我的语法正确吗?
  2. Can I upload multiple images using the above method?我可以使用上述方法上传多张图片吗?

If you have any suggestions or answers, then it will be very helpful.如果您有任何建议或答案,那将非常有帮助。

I would suggest you to use dio.我建议你使用 dio。 It is a better and more powerful http client.是一款更好更强大的http客户端。

https://pub.dev/packages/dio https://pub.dev/packages/dio

You can easily upload multipart files and additionally receive the progress of the upload.您可以轻松上传多部分文件并额外接收上传进度。 Furthermore you can create a httpservice that contains a static Dio, which will be created one time and accessed by getters.此外,您可以创建一个包含 static Dio 的 httpservice,它将被创建一次并由 getter 访问。 So you only need to put your authorization one time at initialization or set interceptors to the client.所以你只需要在初始化时授权一次或者给客户端设置拦截器。

No, you are introducing a subtle error.不,您正在引入一个微妙的错误。 By making the forEach closure async it is automatically returning a future - and will not get executed inline.通过使forEach闭包async ,它会自动返回一个未来 - 并且不会内联执行。

Prefer for to forEach when iterating a list.迭代列表时更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),
    ));
  }

In my case, i had photo as Uint8List and before request i wanted to create a file.就我而言,我有照片作为 Uint8List 并且在请求之前我想创建一个文件。

My problem was missing await on the write function.我的问题是在写入 function 时缺少等待。

await file.writeAsBytes(photo);

So function didn't finish writing probably and request was triggered.所以 function 可能没有完成写入并触发了请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的异常:内容大小低于指定的 contentLength。 已写入 206 字节,但预期为 375482。#228 - Unhandled Exception: Content size below specified contentLength. 206 bytes written but expected 375482. #228 ClientException(内容大小超过指定的 contentLength。10911 字节写入而预期 5965 - ClientException (Content size exceeds specified contentLength. 10911 bytes written while expected 5965 Flutter 在特定正文中上传带有 MultipartRequest 的图像 - Flutter Upload image with MultipartRequest inside specific body 使用MultiPartRequest上传文件在flutter web - Using MultiPartRequest to upload file in flutter web 如何使用 MultipartRequest 提交没有图像的数据? - How to submit data without image using MultipartRequest? 尝试在 flutter 中使用 MultipartRequest 上传文件时出现握手异常 - Handshake Exception when trying to upload a file using MultipartRequest in flutter 如何使用 dart 在 MultiPartRequest 中添加列表? - How to add a list inside MultiPartRequest using dart? 如何在Flutter中取消通过http.MultipartRequest()发送的正在进行的文件上传? - How to cancel ongoing file upload sent with http.MultipartRequest() in Flutter? 文件上传适用于 Thunder Client 和 Chrome,但不适用于 Dio 或 MultipartRequest - File upload works in Thunder Client and Chrome, but not Dio or MultipartRequest 当从 flutter 中的 MultipartRequest 发送图像时无法检测到图像 - Failed to detect the image when an image sent form MultipartRequest in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM