Browse Source

Add URI source support #56

Ben Hsieh 8 years ago
parent
commit
d7b3413daa

+ 25
- 5
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobFS.java View File

@@ -647,12 +647,32 @@ public class RNFetchBlobFS {
647 647
         try {
648 648
             File dest = new File(path);
649 649
             boolean created = dest.createNewFile();
650
-            if(!created) {
651
-                callback.invoke("create file error: failed to create file at path `" + path + "` for its parent path may not exists");
652
-                return;
650
+            if(encoding.equals(RNFetchBlobConst.DATA_ENCODE_URI)) {
651
+                String orgPath = data.replace(RNFetchBlobConst.FILE_PREFIX, "");
652
+                File src = new File(orgPath);
653
+                if(!src.exists()) {
654
+                    callback.invoke("RNfetchBlob writeFileError", "source file : " + data + "not exists");
655
+                    return ;
656
+                }
657
+                FileInputStream fin = new FileInputStream(src);
658
+                OutputStream ostream = new FileOutputStream(dest);
659
+                byte [] buffer = new byte [10240];
660
+                int read = fin.read(buffer);
661
+                while(read > 0) {
662
+                    ostream.write(buffer, 0, read);
663
+                    read = fin.read(buffer);
664
+                }
665
+                fin.close();
666
+                ostream.close();
667
+            }
668
+            else {
669
+                if (!created) {
670
+                    callback.invoke("create file error: failed to create file at path `" + path + "` for its parent path may not exists");
671
+                    return;
672
+                }
673
+                OutputStream ostream = new FileOutputStream(dest);
674
+                ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
653 675
             }
654
-            OutputStream ostream = new FileOutputStream(dest);
655
-            ostream.write(RNFetchBlobFS.stringToBytes(data, encoding));
656 676
             callback.invoke(null, path);
657 677
         } catch(Exception err) {
658 678
             callback.invoke(err.getLocalizedMessage());

+ 4
- 0
src/ios/RNFetchBlob/RNFetchBlob.m View File

@@ -101,6 +101,10 @@ RCT_EXPORT_METHOD(createFile:(NSString *)path data:(NSString *)data encoding:(NS
101 101
     else if([[encoding lowercaseString] isEqualToString:@"base64"]) {
102 102
         fileContent = [[NSData alloc] initWithBase64EncodedData:data options:0];
103 103
     }
104
+    else if([[encoding lowercaseString] isEqualToString:@"uri"]) {
105
+        NSString * orgPath = [data stringByReplacingOccurrencesOfString:FILE_PREFIX withString:@""];
106
+        fileContent = [[NSData alloc] initWithContentsOfFile:orgPath];
107
+    }
104 108
     else {
105 109
         fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
106 110
     }