react-native icon indicating copy to clipboard operation
react-native copied to clipboard

[Android]Upload FormData error

Open TanTan-TT opened this issue 10 years ago • 14 comments

This is my code

  var formData = new FormData();

    var type = "image/png";
    formData.append("name", name);
    formData.append("key", '${filename}');
    formData.append('policy',base64Policy);
    formData.append("OSSAccessKeyId",accessKey);
    formData.append("success_action_status", "200");
    formData.append('signature',sign);
    formData.append("file",{uri,type,name}); // uri, type and name must have all!

    var request = new XMLHttpRequest();
    request.open("POST", ossHost, true);
    request.onreadystatechange = function(status){
      if (request.readyState !== 4) {
        return;
      }

      if (request.status === 200) {
        console.log('success', request.responseText);
      } else {
        console.warn('error',request.responseText);
      }
    }
    request.send(formData);

Will get server error

The body of your POST request is not well-formed multipart/form-data

I found it is a bug for RN or okhttp, because RN send following request

--be1563be-4245-4ac5-8a95-498ba5b57ba8
content-disposition: form-data; name="name"
Content-Length: 22

ic_menu_white_24dp.png
...
--d4653e4a-9a5d-42e5-8a49-fcafbe9c673c
content-disposition: form-data; name="file"; filename="ic_menu_white_24dp.png"
Content-Type: image/png
Content-Length: 92

Noticed that Content-Length: 92, this should not be included in the multipart body according to RFC1867

And then, I searched RN's source code, following is

      @Override
      public long contentLength() {
        try {
          return inputStream.available();
        } catch (IOException e) {
          return 0;
        }
      }

According to okhttp code,


      long contentLength = body.contentLength();
      if (contentLength != -1) {
        sink.writeUtf8("Content-Length: ")
            .writeDecimalLong(contentLength)
            .write(CRLF);
      } else if (countBytes) {
        // We can't measure the body's size without the sizes of its components.
        byteCountBuffer.clear();
        return -1L;
      }

if contentLength != -1, "Content_Length" will be wrote into request.

And then I change RN's code in NetworkingModule.java, following is

    if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) {
        String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING);
        //change code, if use RequestBody.create, okhttp will add "Content-Length"
        final byte[] bytes = bodyValue.getBytes(Charset.forName("UTF-8"));
        final MediaType partContentType1 = partContentType;
        multipartBuilder.addPart(headers,
          new RequestBody() {
            @Override public MediaType contentType() {
              return MediaType.parse(partContentType1 + "; charset=utf-8");
            }

            @Override public long contentLength() throws IOException {
              return -1;
            }

            @Override public void writeTo(BufferedSink sink) throws IOException {
              sink.write(bytes, 0, bytes.length);
            }
          }
        );
      }

and change RequestBodyUtil.java file

public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {
      @Override
      public MediaType contentType() {
        return mediaType;
      }

      //remove following code
      // @Override 
      // public long contentLength() {
      //   try {
      //     return -1;
      //     //return inputStream.available();
      //   } catch (IOException e) {
      //     return 0;
      //   }
      // }

      @Override
      public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
          source = Okio.source(inputStream);
          sink.writeAll(source);
        } finally {
          Util.closeQuietly(source);
        }
      }
    };
  }

And finally it works!

TanTan-TT avatar Dec 21 '15 01:12 TanTan-TT

Hey TanTan-TT, thanks for reporting this issue!

React Native, as you've probably heard, is getting really popular and truth is we're getting a bit overwhelmed by the activity surrounding it. There are just too many issues for us to manage properly.

  • If you don't know how to do something or not sure whether some behavior is expected or a bug, please ask on StackOverflow with the tag react-native or for more real time interactions, ask on Discord in the #react-native channel.
  • If this is a feature request or a bug that you would like to be fixed, please report it on Product Pains. It has a ranking feature that lets us focus on the most important issues the community is experiencing.
  • We welcome clear issues and PRs that are ready for in-depth discussion. Please provide screenshots where appropriate and always mention the version of React Native you're using. Thank you for your contributions!

facebook-github-bot avatar Dec 21 '15 01:12 facebook-github-bot

@satya164 This is my analysis.

TanTan-TT avatar Dec 21 '15 01:12 TanTan-TT

What version of RN are you using ?

AdamGorkoz avatar Dec 22 '15 07:12 AdamGorkoz

Thanks @TanTan-TT . Can you send a PR?

satya164 avatar Dec 22 '15 07:12 satya164

@turka50 v.16

TanTan-TT avatar Dec 23 '15 06:12 TanTan-TT

@satya164 According to reply from okhttp Maybe it is an issue by webserver. But I believe maybe some cloud providers have this issue, so do you think it is necessary to PR this?

TanTan-TT avatar Dec 23 '15 06:12 TanTan-TT

Hi there! This issue is being closed because it has been inactive for a while.

But don't worry, it will live on with ProductPains! Check out its new home: https://productpains.com/post/react-native/androidupload-formdata-error

ProductPains helps the community prioritize the most important issues thanks to its voting feature. It is easy to use - just login with GitHub.

Also, if this issue is a bug, please consider sending a PR with a fix. We're a small team and rely on the community for bug fixes of issues that don't affect fb apps.

mkonicek avatar Apr 10 '16 16:04 mkonicek

ios has this problem. react-native version 0.25

timzaak avatar May 12 '16 09:05 timzaak

@timzaak It could be caused by issue 7329 But it has been fixed. You can wait it until 0.26

TanTan-TT avatar May 12 '16 13:05 TanTan-TT

@TanTan-TT with that commit, the upload also failed. I use the native code to upload to ali oss. And with Android, I also write the native code. I try some third part, but all of the failed.

timzaak avatar May 13 '16 11:05 timzaak

@timzaak I got it. This is aliyun's bug. It cannot support with additional content-type when multipart sumbit

TanTan-TT avatar May 14 '16 00:05 TanTan-TT

@TanTan-TT how to fix aliyun's bug?

suinia avatar Oct 30 '16 03:10 suinia

write native code. and if possible, ues aliyun sdk. @suinia

timzaak avatar Oct 30 '16 04:10 timzaak

PR is necessary! The behavior on iOS and Android should be consistent. As @TanTan-TT said, some servers may be buggy, so what can developers do? @mkonicek

sunnylqm avatar Nov 25 '16 03:11 sunnylqm