Skip to content

UTF-8 error when sending non UTF-8 encoded body #171

@UlrichRaab

Description

@UlrichRaab

Describe the bug
I must use a AWS S3 presigned upload URL to upload an image to S3 (PUT request). The request body is the raw bytes of that image. The bytes are not UTF-8 encoded. The request fails with FormatException: Invalid UTF-8 byte (at offset 0)

My code for the request:

final bytes = await File(file.path).readAsBytes();
final url = Uri.parse(uploadUrl);
final request = Request('PUT', url)
  ..headers['Content-Type'] = file.mimeType
  ..headers['x-amz-checksum-sha256'] = file.sha256
  ..bodyBytes = bytes;
final stream = await httpClient.send(request);
final response = await Response.fromStream(stream);
return UploadFileResponse.fromHttpResponse(response);

The stacktrace:

Upload image failed
I/flutter (28409):FormatException: Invalid UTF-8 byte (at offset 0)
I/flutter (28409): ↳ #0      _Utf8Decoder.convertSingle (dart:convert-patch/convert_patch.dart:1860:7)
I/flutter (28409):   #1      Utf8Decoder.convert (dart:convert/utf.dart:350:37)
I/flutter (28409):   #2      Utf8Codec.decode (dart:convert/utf.dart:63:20)
I/flutter (28409):   #3      Request.body (package:http/src/request.dart:102:31)
I/flutter (28409):   #4      RequestCopyWith.copyWith (package:http_interceptor/extensions/request.dart:24:20)
I/flutter (28409):   #5      BaseRequestCopyWith.copyWith (package:http_interceptor/extensions/base_request.dart:38:47)
I/flutter (28409):   #6      InterceptedClient._interceptRequest (package:http_interceptor/http/intercepted_client.dart:311:46)

I think the error happens because you copy the body in your copyWith extension of Request. Using bodyBytes instead should fix the problem.

To Reproduce
Steps to reproduce the behavior:

  1. Try to send raw bytes to an endpoint using a PUT request

Expected behavior
No UTF-8 Format exception

Screenshots
No screenshot

Please complete the following information):

  • Flutter version: [3.38.8]
  • IDE [VS Code]
  • http_interceptor Version [2.0.0]

Additional context
Add any other context about the problem here.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions