Skip to content

Commit ef490b6

Browse files
author
Pedro Belo
committed
handle different types of image urls
avoid issue getting a path for some image urls returned by the intent on Android 4.4+ - just create a temp file for these
1 parent 19c45e9 commit ef490b6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

android/src/main/java/com/imagepicker/ImagePickerModule.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import java.io.FileInputStream;
3030
import java.io.ByteArrayOutputStream;
3131
import java.io.FileNotFoundException;
32+
import java.io.OutputStream;
3233
import java.util.List;
3334
import java.util.ArrayList;
3435
import java.io.FileOutputStream;
@@ -220,6 +221,18 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) {
220221
: data.getData();
221222

222223
String realPath = getRealPathFromURI(uri);
224+
if (realPath == null) {
225+
try {
226+
File file = createFileFromURI(uri);
227+
realPath = file.getAbsolutePath();
228+
uri = Uri.fromFile(file);
229+
}
230+
catch(Exception e) {
231+
response.putString("error", "Could not read photo");
232+
mCallback.invoke(response);
233+
return;
234+
}
235+
}
223236

224237
boolean isUrl = true;
225238
try {
@@ -300,6 +313,26 @@ private String getRealPathFromURI(Uri uri) {
300313
return result;
301314
}
302315

316+
private File createFileFromURI(Uri uri) throws Exception {
317+
File file = new File(mReactContext.getCacheDir(), "photo-" + uri.getLastPathSegment());
318+
InputStream input = mReactContext.getContentResolver().openInputStream(uri);
319+
OutputStream output = new FileOutputStream(file);
320+
321+
try {
322+
byte[] buffer = new byte[4 * 1024];
323+
int read;
324+
while ((read = input.read(buffer)) != -1) {
325+
output.write(buffer, 0, read);
326+
}
327+
output.flush();
328+
} finally {
329+
output.close();
330+
input.close();
331+
}
332+
333+
return file;
334+
}
335+
303336
private String getBase64StringFromFile (String absoluteFilePath) {
304337
InputStream inputStream = null;
305338
try {

0 commit comments

Comments
 (0)