├── .gitignore ├── FileUpload.m ├── LICENSE ├── README.md ├── index.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | pids 11 | logs 12 | results 13 | 14 | npm-debug.log 15 | node_modules 16 | 17 | coverage.html 18 | /coverage 19 | -------------------------------------------------------------------------------- /FileUpload.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | #import 4 | #import 5 | 6 | #import "RCTBridgeModule.h" 7 | #import "RCTLog.h" 8 | 9 | @interface FileUpload : NSObject 10 | @end 11 | 12 | @implementation FileUpload 13 | 14 | RCT_EXPORT_MODULE(); 15 | 16 | RCT_EXPORT_METHOD(upload:(NSDictionary *)obj callback:(RCTResponseSenderBlock)callback) 17 | { 18 | NSString *uploadUrl = obj[@"uploadUrl"]; 19 | NSDictionary *headers = obj[@"headers"]; 20 | NSDictionary *fields = obj[@"fields"]; 21 | NSArray *files = obj[@"files"]; 22 | NSString *method = obj[@"method"]; 23 | 24 | if ([method isEqualToString:@"POST"] || [method isEqualToString:@"PUT"]) { 25 | } else { 26 | method = @"POST"; 27 | } 28 | 29 | NSURL *url = [NSURL URLWithString:uploadUrl]; 30 | NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 31 | [req setHTTPMethod:method]; 32 | 33 | // set headers 34 | NSString *formBoundaryString = [self generateBoundaryString]; 35 | NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", formBoundaryString]; 36 | [req setValue:contentType forHTTPHeaderField:@"Content-Type"]; 37 | for (NSString *key in headers) { 38 | id val = [headers objectForKey:key]; 39 | if ([val respondsToSelector:@selector(stringValue)]) { 40 | val = [val stringValue]; 41 | } 42 | if (![val isKindOfClass:[NSString class]]) { 43 | continue; 44 | } 45 | [req setValue:val forHTTPHeaderField:key]; 46 | } 47 | 48 | 49 | NSData *formBoundaryData = [[NSString stringWithFormat:@"--%@\r\n", formBoundaryString] dataUsingEncoding:NSUTF8StringEncoding]; 50 | NSMutableData* reqBody = [NSMutableData data]; 51 | 52 | // add fields 53 | for (NSString *key in fields) { 54 | id val = [fields objectForKey:key]; 55 | if ([val respondsToSelector:@selector(stringValue)]) { 56 | val = [val stringValue]; 57 | } 58 | if (![val isKindOfClass:[NSString class]]) { 59 | continue; 60 | } 61 | 62 | [reqBody appendData:formBoundaryData]; 63 | [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]]; 64 | [reqBody appendData:[val dataUsingEncoding:NSUTF8StringEncoding]]; 65 | [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 66 | } 67 | 68 | // add files 69 | for (NSDictionary *file in files) { 70 | NSString *name = file[@"name"]; 71 | NSString *filename = file[@"filename"]; 72 | NSString *filepath = file[@"filepath"]; 73 | NSString *filetype = file[@"filetype"]; 74 | 75 | NSData *fileData = nil; 76 | 77 | NSLog(@"filepath: %@", filepath); 78 | if ([filepath hasPrefix:@"assets-library:"]) { 79 | NSURL *assetUrl = [[NSURL alloc] initWithString:filepath]; 80 | ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; 81 | 82 | __block BOOL isFinished = NO; 83 | __block NSData * tempData = nil; 84 | [library assetForURL:assetUrl resultBlock:^(ALAsset *asset) { 85 | ALAssetRepresentation *rep = [asset defaultRepresentation]; 86 | 87 | CGImageRef fullScreenImageRef = [rep fullScreenImage]; 88 | UIImage *image = [UIImage imageWithCGImage:fullScreenImageRef]; 89 | tempData = UIImagePNGRepresentation(image); 90 | isFinished = YES; 91 | } failureBlock:^(NSError *error) { 92 | NSLog(@"ALAssetsLibrary assetForURL error:%@", error); 93 | isFinished = YES; 94 | }]; 95 | while (!isFinished) { 96 | [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]]; 97 | } 98 | fileData = tempData; 99 | } else if ([filepath hasPrefix:@"data:"] || [filepath hasPrefix:@"file:"]) { 100 | NSURL *fileUrl = [[NSURL alloc] initWithString:filepath]; 101 | fileData = [NSData dataWithContentsOfURL: fileUrl]; 102 | } else { 103 | fileData = [NSData dataWithContentsOfFile:filepath]; 104 | } 105 | 106 | [reqBody appendData:formBoundaryData]; 107 | [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name.length ? name : filename, filename] dataUsingEncoding:NSUTF8StringEncoding]]; 108 | 109 | if (filetype) { 110 | [reqBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", filetype] dataUsingEncoding:NSUTF8StringEncoding]]; 111 | } else { 112 | [reqBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", [self mimeTypeForPath:filename]] dataUsingEncoding:NSUTF8StringEncoding]]; 113 | } 114 | 115 | [reqBody appendData:[[NSString stringWithFormat:@"Content-Length: %ld\r\n\r\n", (long)[fileData length]] dataUsingEncoding:NSUTF8StringEncoding]]; 116 | [reqBody appendData:fileData]; 117 | [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 118 | } 119 | 120 | // add end boundary 121 | NSData* end = [[NSString stringWithFormat:@"--%@--\r\n", formBoundaryString] dataUsingEncoding:NSUTF8StringEncoding]; 122 | [reqBody appendData:end]; 123 | 124 | // send request 125 | [req setHTTPBody:reqBody]; 126 | NSHTTPURLResponse *response = nil; 127 | NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:nil]; 128 | NSInteger statusCode = [response statusCode]; 129 | NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 130 | 131 | NSDictionary *res=[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInteger:statusCode],@"status",returnString,@"data",nil]; 132 | 133 | callback(@[[NSNull null], res]); 134 | } 135 | 136 | - (NSString *)generateBoundaryString 137 | { 138 | NSString *uuid = [[NSUUID UUID] UUIDString]; 139 | return [NSString stringWithFormat:@"----%@", uuid]; 140 | } 141 | 142 | - (NSString *)mimeTypeForPath:(NSString *)filepath 143 | { 144 | NSString *fileExtension = [filepath pathExtension]; 145 | NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL); 146 | NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); 147 | 148 | if (contentType) { 149 | return contentType; 150 | } 151 | return @"application/octet-stream"; 152 | } 153 | 154 | @end 155 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Liucw 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-file-upload [![NPM version](https://img.shields.io/npm/v/react-native-file-upload.svg?style=flat-square)](https://www.npmjs.com/package/react-native-file-upload) 2 | 3 | > React Native latest version had support file upload, the package is **deprecated**, detail see [#4](/../../issues/4) [#7](/../../issues/7). 4 | 5 | A file upload plugin for react-native written by Objective-C. 6 | 7 | * Support to upload multiple files at a time 8 | * Support to files and fields 9 | 10 | ## Getting started 11 | 12 | 1. `npm install react-native-file-upload --save` 13 | 2. In XCode, in the project navigator, right click `your project` ➜ `Add Files to [your project's name]` 14 | 3. Go to `node_modules` ➜ `react-native-file-upload` and add `FileUpload.m` 15 | 4. Run your project (`Cmd+R`) 16 | 17 | ## Usage 18 | 19 | All you need is to export module `var FileUpload = require('NativeModules').FileUpload;` and direct invoke `FileUpload.upload`. 20 | 21 | ```javascript 22 | 'use strict'; 23 | 24 | var React = require('react-native'); 25 | var FileUpload = require('NativeModules').FileUpload; 26 | 27 | var { 28 | AppRegistry, 29 | StyleSheet, 30 | Text, 31 | View, 32 | } = React; 33 | 34 | var FileUploadDemo = React.createClass({ 35 | componentDidMount: function() { 36 | var obj = { 37 | uploadUrl: 'http://127.0.0.1:3000', 38 | method: 'POST', // default 'POST',support 'POST' and 'PUT' 39 | headers: { 40 | 'Accept': 'application/json', 41 | }, 42 | fields: { 43 | 'hello': 'world', 44 | }, 45 | files: [ 46 | { 47 | name: 'one', // optional, if none then `filename` is used instead 48 | filename: 'one.w4a', // require, file name 49 | filepath: '/xxx/one.w4a', // require, file absoluete path 50 | filetype: 'audio/x-m4a', // options, if none, will get mimetype from `filepath` extension 51 | }, 52 | ] 53 | }; 54 | FileUpload.upload(obj, function(err, result) { 55 | console.log('upload:', err, result); 56 | }) 57 | }, 58 | render: function() { 59 | return ( 60 | 61 | 62 | Welcome to React Native! 63 | 64 | 65 | ); 66 | } 67 | }); 68 | 69 | var styles = StyleSheet.create({ 70 | container: { 71 | flex: 1, 72 | justifyContent: 'center', 73 | alignItems: 'center', 74 | backgroundColor: '#F5FCFF', 75 | }, 76 | welcome: { 77 | fontSize: 20, 78 | textAlign: 'center', 79 | margin: 10, 80 | }, 81 | }); 82 | 83 | AppRegistry.registerComponent('FileUploadDemo', () => FileUploadDemo); 84 | ``` 85 | 86 | ## License 87 | 88 | MIT 89 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/booxood/react-native-file-upload/ee0cfdcc6a3876d6ea6894b365224a81e9f8c18b/index.js -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-file-upload", 3 | "version": "1.0.4", 4 | "description": "A file upload plugin for react-native", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/booxood/react-native-file-upload.git" 12 | }, 13 | "keywords": [ 14 | "react-component", 15 | "react-native", 16 | "ios", 17 | "file", 18 | "upload" 19 | ], 20 | "peerDependencies": { 21 | "react-native": ">=0.4.2" 22 | }, 23 | "author": "Liucw", 24 | "license": "MIT", 25 | "bugs": { 26 | "url": "https://github.com/booxood/react-native-file-upload/issues" 27 | }, 28 | "homepage": "https://github.com/booxood/react-native-file-upload" 29 | } 30 | --------------------------------------------------------------------------------