-
Notifications
You must be signed in to change notification settings - Fork 24k
/
FileReaderModule.java
89 lines (70 loc) · 2.32 KB
/
FileReaderModule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.modules.blob;
import android.util.Base64;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.module.annotations.ReactModule;
@ReactModule(name = FileReaderModule.NAME)
public class FileReaderModule extends ReactContextBaseJavaModule {
protected static final String NAME = "FileReaderModule";
private static final String ERROR_INVALID_BLOB = "ERROR_INVALID_BLOB";
public FileReaderModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return NAME;
}
private BlobModule getBlobModule() {
return getReactApplicationContext().getNativeModule(BlobModule.class);
}
@ReactMethod
public void readAsText(ReadableMap blob, String encoding, Promise promise) {
byte[] bytes = getBlobModule().resolve(
blob.getString("blobId"),
blob.getInt("offset"),
blob.getInt("size"));
if (bytes == null) {
promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid");
return;
}
try {
promise.resolve(new String(bytes, encoding));
} catch (Exception e) {
promise.reject(e);
}
}
@ReactMethod
public void readAsDataURL(ReadableMap blob, Promise promise) {
byte[] bytes = getBlobModule().resolve(
blob.getString("blobId"),
blob.getInt("offset"),
blob.getInt("size"));
if (bytes == null) {
promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid");
return;
}
try {
StringBuilder sb = new StringBuilder();
sb.append("data:");
if (blob.hasKey("type") && !blob.getString("type").isEmpty()) {
sb.append(blob.getString("type"));
} else {
sb.append("application/octet-stream");
}
sb.append(";base64,");
sb.append(Base64.encodeToString(bytes, Base64.NO_WRAP));
promise.resolve(sb.toString());
} catch (Exception e) {
promise.reject(e);
}
}
}