浏览代码

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

Ben Hsieh 9 年前
父节点
当前提交
be59f5ebc4

+ 47
- 31
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java 查看文件

22
 import java.io.ByteArrayOutputStream;
22
 import java.io.ByteArrayOutputStream;
23
 import java.io.File;
23
 import java.io.File;
24
 
24
 
25
+import cz.msebera.android.httpclient.HttpEntity;
26
+import cz.msebera.android.httpclient.entity.AbstractHttpEntity;
25
 import cz.msebera.android.httpclient.entity.ByteArrayEntity;
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
 public class RNFetchBlob extends ReactContextBaseJavaModule {
33
 public class RNFetchBlob extends ReactContextBaseJavaModule {
28
 
34
 
35
+    String filePathPrefix = "RNFetchBlob-file://";
29
 
36
 
30
     public RNFetchBlob(ReactApplicationContext reactContext) {
37
     public RNFetchBlob(ReactApplicationContext reactContext) {
31
         super(reactContext);
38
         super(reactContext);
41
 
48
 
42
         WritableArray results = Arguments.createArray();
49
         WritableArray results = Arguments.createArray();
43
         ReactApplicationContext ctx = this.getReactApplicationContext();
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
     @ReactMethod
61
     @ReactMethod
70
      * @param encoding Stream encoding, should be one of `base64`, `ascii`, and `utf8`
78
      * @param encoding Stream encoding, should be one of `base64`, `ascii`, and `utf8`
71
      * @param bufferSize Stream buffer size, default to 1024 or 1026(base64).
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
         RNFetchBlobFS fs = new RNFetchBlobFS(this.getReactApplicationContext());
82
         RNFetchBlobFS fs = new RNFetchBlobFS(this.getReactApplicationContext());
75
         fs.readStream(path, encoding, bufferSize);
83
         fs.readStream(path, encoding, bufferSize);
76
     }
84
     }
86
 
94
 
87
             // set params
95
             // set params
88
             RequestParams params = new RequestParams();
96
             RequestParams params = new RequestParams();
89
-            ByteArrayEntity entity = null;
97
+            AbstractHttpEntity entity = null;
90
 
98
 
91
             // set params
99
             // set params
92
             for (String paramName : uri.getQueryParameterNames()) {
100
             for (String paramName : uri.getQueryParameterNames()) {
102
 
110
 
103
             // set body for POST and PUT
111
             // set body for POST and PUT
104
             if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
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
                 entity.setContentType(headers.getString("Content-Type"));
124
                 entity.setContentType(headers.getString("Content-Type"));
108
             }
125
             }
109
 
126
 
146
 
163
 
147
             // set params
164
             // set params
148
             RequestParams params = new RequestParams();
165
             RequestParams params = new RequestParams();
149
-            ByteArrayEntity entity = null;
150
-
166
+//            ByteArrayEntity entity = null;
167
+            HttpEntity entity = null;
151
             // set params
168
             // set params
152
             for (String paramName : uri.getQueryParameterNames()) {
169
             for (String paramName : uri.getQueryParameterNames()) {
153
                 params.put(paramName, uri.getQueryParameter(paramName));
170
                 params.put(paramName, uri.getQueryParameter(paramName));
164
 
181
 
165
             // set body for POST and PUT
182
             // set body for POST and PUT
166
             if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
183
             if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
167
-
168
                 Long tsLong = System.currentTimeMillis()/1000;
184
                 Long tsLong = System.currentTimeMillis()/1000;
169
                 String ts = tsLong.toString();
185
                 String ts = tsLong.toString();
170
-                ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
171
                 String boundary = "RNFetchBlob".concat(ts);
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
                     ReadableMap map = body.getMap(i);
190
                     ReadableMap map = body.getMap(i);
174
                     String name = map.getString("name");
191
                     String name = map.getString("name");
192
+                    if(!map.hasKey("data"))
193
+                        continue;
194
+                    String data = map.getString("data");
175
                     // file field
195
                     // file field
176
                     if(map.hasKey("filename")) {
196
                     if(map.hasKey("filename")) {
177
                         String filename = map.getString("filename");
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
                     // data field
208
                     // data field
186
                     else {
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
                 req.addHeader("Content-Type", headers.getString("Content-Type") + "; charset=utf8; boundary=" + boundary);
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 查看文件

15
         if(options == null)
15
         if(options == null)
16
             return;
16
             return;
17
         this.fileCache = options.hasKey("fileCache") ? options.getBoolean("fileCache") : false;
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
         this.appendExt = options.hasKey("appendExt") ? options.getString("appendExt") : "";
19
         this.appendExt = options.hasKey("appendExt") ? options.getString("appendExt") : "";
20
 
20
 
21
     }
21
     }

+ 3
- 3
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java 查看文件

31
         this.mCtx = ctx;
31
         this.mCtx = ctx;
32
         this.emitter = ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
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
         AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
36
         AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
37
             @Override
37
             @Override
38
             protected Integer doInBackground(String ... args) {
38
             protected Integer doInBackground(String ... args) {
81
                 return null;
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
     void emitStreamEvent(String streamName, String event, String data) {
87
     void emitStreamEvent(String streamName, String event, String data) {