http icon indicating copy to clipboard operation
http copied to clipboard

Sending a .wav file through FormData using MultipartFile adds headers which corrupt the file

Open agenthesh opened this issue 2 years ago • 1 comments

Please check here for a write-up on this bug.

I have found a solution to this bug, documenting this here in order to help other people if they may face the same issue.

I extended the MultipartRequest, adding in my own custom logic to the content length, and finalize methods. The code for what I have done is below.

class CustomMultiPartRequest extends http.MultipartRequest {
  final http.Client _inner = http.Client();

  CustomMultiPartRequest(super.method, super.url);

  @override
  Future<http.StreamedResponse> send() {
    headers.clear(); // Remove all headers
    return _inner.send(this);
  }

  @override
  int get contentLength {
    var length = 0;

    for (var file in files) {
      length += file.length;
    }

    return length;
  }

  Stream<List<int>> _finalizeFiles() async* {
    for (var file in files) {
      yield* file.finalize();
    }
  }

  @override
  http.ByteStream finalize() {
    super.finalize();

    return http.ByteStream(_finalizeFiles());
  }
}

An example way to use this class.

var request = CustomMultiPartRequest('PUT', Uri.parse(uploadUrl));

      request.files.add(await http.MultipartFile.fromPath(
        '',
        wavFile.path,
        contentType: MediaType('', ''),
      ));

      final resp = await request.send();

Obviously, this is not a well written extension, but it works for my use case. No headers are added to the file, and thus the file is not corrupted anymore. Also, I am not certain if this is the best way to solve this issue, if there is another way, please let me know.

agenthesh avatar Jun 22 '23 19:06 agenthesh

@agenthesh I'm sorry but I don't understand your bug report.

MultipartRequest is generating multipart/form-data requests as described by RFC-7578 (example) so the internal headers are expected.

Do you have a simple example that highlights the bug?

brianquinlan avatar Jun 28 '24 21:06 brianquinlan

Without additional information we're not able to resolve this issue. Feel free to add more info or respond to any questions above and we can reopen the case. Thanks for your contribution!

github-actions[bot] avatar Jul 27 '24 08:07 github-actions[bot]