From 3b7fbb8f9b5d838233af05880dbcc237acf2b60b Mon Sep 17 00:00:00 2001 From: daisy1754 Date: Tue, 18 Apr 2023 04:19:14 -0700 Subject: [PATCH] Fix RequestBodyUtil for older version of Android (M or before) (#28399) Summary: This is bugfix for following code in RequestBodyUtil.java. ``` stream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); ``` This throws IllegalArgumentException in Android M or before. It seems in old version of JVM it internally casts third argument to integer so when you pass value that is larger than Integer.MAX_VALUE app would crash. See: https://bugs.openjdk.java.net/browse/JDK-5105464 https://stackoverflow.com/questions/55696035/thrown-illegalargumentexception-when-using-java-nio ## Changelog [Android] [Fixed] Fix issue downloading request body via remote URL Pull Request resolved: https://github.com/facebook/react-native/pull/28399 Test Plan: Run following code on Android M or before. It would crash w/o this PR but it won't with this PR. ``` const body = new FormData(); const image = { uri: "https://reactnative.dev/img/showcase/facebook.png", path: null }; body.append('user[img]', fileBody(image)); fetch("https://example.com", { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data;', }, body: body }); ``` Reviewed By: christophpurrer, cipolleschi Differential Revision: D45057263 Pulled By: cortinico fbshipit-source-id: e0306eb157a5aa92619ac51e67d106b8651a0ba7 --- .../facebook/react/modules/network/RequestBodyUtil.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java index 57fa7c58980255..4a56e92a88796a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/RequestBodyUtil.java @@ -11,6 +11,7 @@ import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; +import android.os.Build; import android.util.Base64; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; @@ -96,7 +97,12 @@ private static InputStream getDownloadFileInputStream(Context context, Uri uri) try { final FileOutputStream stream = new FileOutputStream(file); try { - stream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); + long maxBytes = Long.MAX_VALUE; + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { + // Old version of Android internally cast value to integer + maxBytes = (long) Integer.MAX_VALUE; + } + stream.getChannel().transferFrom(channel, 0, maxBytes); return new FileInputStream(file); } finally { stream.close();