Ver código fonte

#2 #3 add upload-from-storage android implementation

Ben Hsieh 8 anos atrás
pai
commit
be59f5ebc4

+ 47
- 31
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java Ver arquivo

@@ -22,10 +22,17 @@ import com.loopj.android.http.RequestParams;
22 22
 import java.io.ByteArrayOutputStream;
23 23
 import java.io.File;
24 24
 
25
+import cz.msebera.android.httpclient.HttpEntity;
26
+import cz.msebera.android.httpclient.entity.AbstractHttpEntity;
25 27
 import cz.msebera.android.httpclient.entity.ByteArrayEntity;
28
+import cz.msebera.android.httpclient.entity.ContentType;
29
+import cz.msebera.android.httpclient.entity.FileEntity;
30
+import cz.msebera.android.httpclient.entity.mime.MultipartEntityBuilder;
31
+import cz.msebera.android.httpclient.entity.mime.content.ContentBody;
26 32
 
27 33
 public class RNFetchBlob extends ReactContextBaseJavaModule {
28 34
 
35
+    String filePathPrefix = "RNFetchBlob-file://";
29 36
 
30 37
     public RNFetchBlob(ReactApplicationContext reactContext) {
31 38
         super(reactContext);
@@ -41,13 +48,14 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
41 48
 
42 49
         WritableArray results = Arguments.createArray();
43 50
         ReactApplicationContext ctx = this.getReactApplicationContext();
44
-        results.pushString(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
45
-        results.pushString(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
46
-        results.pushString(String.valueOf(ctx.getFilesDir()));
47
-        results.pushString(String.valueOf(ctx.getCacheDir()));
48
-        results.pushString(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)));
49
-        results.pushString(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));
50
-        callback.invoke(results);
51
+        callback.invoke(
52
+                String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)),
53
+                String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)),
54
+                String.valueOf(ctx.getFilesDir()),
55
+                String.valueOf(ctx.getCacheDir()),
56
+                String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)),
57
+                String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))
58
+        );
51 59
     }
52 60
 
53 61
     @ReactMethod
@@ -70,7 +78,7 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
70 78
      * @param encoding Stream encoding, should be one of `base64`, `ascii`, and `utf8`
71 79
      * @param bufferSize Stream buffer size, default to 1024 or 1026(base64).
72 80
      */
73
-    public void readStream(String path, String encoding, String bufferSize) {
81
+    public void readStream(String path, String encoding, int bufferSize) {
74 82
         RNFetchBlobFS fs = new RNFetchBlobFS(this.getReactApplicationContext());
75 83
         fs.readStream(path, encoding, bufferSize);
76 84
     }
@@ -86,7 +94,7 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
86 94
 
87 95
             // set params
88 96
             RequestParams params = new RequestParams();
89
-            ByteArrayEntity entity = null;
97
+            AbstractHttpEntity entity = null;
90 98
 
91 99
             // set params
92 100
             for (String paramName : uri.getQueryParameterNames()) {
@@ -102,8 +110,17 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
102 110
 
103 111
             // set body for POST and PUT
104 112
             if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
105
-                byte [] blob = Base64.decode(body, 0);
106
-                entity = new ByteArrayEntity(blob);
113
+
114
+                byte [] blob;
115
+                // upload from storage
116
+                if(body.startsWith(filePathPrefix)) {
117
+                    String filePath = body.substring(filePathPrefix.length());
118
+                    entity = new FileEntity(new File(filePath));
119
+                }
120
+                else {
121
+                    blob = Base64.decode(body, 0);
122
+                    entity = new ByteArrayEntity(blob);
123
+                }
107 124
                 entity.setContentType(headers.getString("Content-Type"));
108 125
             }
109 126
 
@@ -146,8 +163,8 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
146 163
 
147 164
             // set params
148 165
             RequestParams params = new RequestParams();
149
-            ByteArrayEntity entity = null;
150
-
166
+//            ByteArrayEntity entity = null;
167
+            HttpEntity entity = null;
151 168
             // set params
152 169
             for (String paramName : uri.getQueryParameterNames()) {
153 170
                 params.put(paramName, uri.getQueryParameter(paramName));
@@ -164,37 +181,36 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
164 181
 
165 182
             // set body for POST and PUT
166 183
             if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
167
-
168 184
                 Long tsLong = System.currentTimeMillis()/1000;
169 185
                 String ts = tsLong.toString();
170
-                ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
171 186
                 String boundary = "RNFetchBlob".concat(ts);
172
-                for(int i =0; i<body.size() ; i++) {
187
+                MultipartEntityBuilder form = MultipartEntityBuilder.create();
188
+                form.setBoundary(boundary);
189
+                for( int i = 0; i< body.size(); i++) {
173 190
                     ReadableMap map = body.getMap(i);
174 191
                     String name = map.getString("name");
192
+                    if(!map.hasKey("data"))
193
+                        continue;
194
+                    String data = map.getString("data");
175 195
                     // file field
176 196
                     if(map.hasKey("filename")) {
177 197
                         String filename = map.getString("filename");
178
-                        byte [] file = Base64.decode(map.getString("data"), 0);
179
-                        outputStream.write(String.format("--%s\r\n", boundary).getBytes("UTF-8"));
180
-                        outputStream.write(("Content-Disposition: form-data; name=\""+name+"\"; filename=\""+filename+"\"\r\n").getBytes("UTF-8"));
181
-                        outputStream.write(String.format("Content-Type: application/octet-stream\r\n\r\n").getBytes());
182
-                        outputStream.write(file);
183
-                        outputStream.write("\r\n".getBytes());
198
+                        // upload from storage
199
+                        if(data.startsWith(filePathPrefix)) {
200
+                            File file = new File(data.substring(filePathPrefix.length()));
201
+                            form.addBinaryBody(name, file, ContentType.APPLICATION_OCTET_STREAM, filename);
202
+                        }
203
+                        // base64 embedded file content
204
+                        else {
205
+                            form.addBinaryBody(name, Base64.decode(data, 0), ContentType.APPLICATION_OCTET_STREAM, filename);
206
+                        }
184 207
                     }
185 208
                     // data field
186 209
                     else {
187
-                        String data = map.getString("data");
188
-                        outputStream.write(String.format("--%s\r\n", boundary).getBytes("UTF-8"));
189
-                        outputStream.write(String.format("Content-Disposition: form-data; name=\""+name+"\"; \r\n").getBytes("UTF-8"));
190
-                        outputStream.write(String.format("Content-Type: text/plain\r\n\r\n").getBytes());
191
-                        outputStream.write((data+"\r\n").getBytes());
210
+                        form.addTextBody(name, map.getString("data"));
192 211
                     }
193 212
                 }
194
-                outputStream.write(String.format("--%s--\r\n", boundary).getBytes());
195
-                byte bodyBytes[] = outputStream.toByteArray( );
196
-                entity = new ByteArrayEntity(bodyBytes);
197
-                entity.setContentType(headers.getString("Content-Type") + "; charset=utf8; boundary=" + boundary);
213
+                entity = form.build();
198 214
                 req.addHeader("Content-Type", headers.getString("Content-Type") + "; charset=utf8; boundary=" + boundary);
199 215
             }
200 216
 

+ 1
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobConfig.java Ver arquivo

@@ -15,7 +15,7 @@ public class RNFetchBlobConfig {
15 15
         if(options == null)
16 16
             return;
17 17
         this.fileCache = options.hasKey("fileCache") ? options.getBoolean("fileCache") : false;
18
-            this.path = options.hasKey("path") ? options.getString("path") : null;
18
+        this.path = options.hasKey("path") ? options.getString("path") : null;
19 19
         this.appendExt = options.hasKey("appendExt") ? options.getString("appendExt") : "";
20 20
 
21 21
     }

+ 3
- 3
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java Ver arquivo

@@ -31,8 +31,8 @@ public class RNFetchBlobFS {
31 31
         this.mCtx = ctx;
32 32
         this.emitter = ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
33 33
     }
34
-    
35
-    public void readStream( String path, String encoding, String bufferSize) {
34
+
35
+    public void readStream( String path, String encoding, int bufferSize) {
36 36
         AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
37 37
             @Override
38 38
             protected Integer doInBackground(String ... args) {
@@ -81,7 +81,7 @@ public class RNFetchBlobFS {
81 81
                 return null;
82 82
             }
83 83
         };
84
-        task.execute(path, encoding, bufferSize);
84
+        task.execute(path, encoding, String.valueOf(bufferSize));
85 85
     }
86 86
 
87 87
     void emitStreamEvent(String streamName, String event, String data) {