Skip to content

support Android #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ xcuserdata
*.xccheckout
*.moved-aside
*.xcuserstate
*.vscode
76 changes: 58 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,50 @@
# react-native-uploader
A React Native module for uploading files and camera roll assets. Supports progress notification.

# Do you absolutely need this?
You can use file upload with `fetch` and if you want progress bar, you can use xhr. Read my post [How to upload photo/file in react-native](https://github.com/g6ling/React-Native-Tips/tree/master/How_to_upload_photo%2Cfile_in%20react-native). Even after read my post, but you are not enough, read the following.

## Install
### Use rnpm
1. `npm install react-native-uploader --save`
2. `rnpm link react-native-uploader`


If you don't want use rnpm, do this
### iOS
1. `npm install react-native-uploader --save`
2. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]`
3. Go to `node_modules` ➜ `react-native-uploader` ➜ `RNUploader` and add `RNUploader.xcodeproj`
4. In XCode, in the project navigator, select your project. Add `libRNUploader.a` to your project's `Build Phases` ➜ `Link Binary With Libraries`
5. Run your project (`Cmd+R`)

### Android
1. Add to your settings.gradle:
```
include ':RNFileTransfer', ':app'
project(':RNFileTransfer').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-file-transfer-android/android')
```

2. Add to your android/build.gradle:
```
dependencies {
...
compile project(':RNFileTransfer')
}
```

3. Add to MainActivity.java
```
import com.burlap.filetransfer.FileTransferPackage;
...
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.addPackage(new FileTransferPackage())
```

## Example
See ./examples/UploadFromCameraRoll

Expand All @@ -18,10 +53,10 @@ See ./examples/UploadFromCameraRoll

## Usage
```javascript
var RNUploader = require('NativeModules').RNUploader;
var RNUploader = require('react-native-uploader');

var {
StyleSheet,
StyleSheet,
Component,
View,
DeviceEventEmitter,
Expand All @@ -35,7 +70,7 @@ componentDidMount(){
let bytesWritten = data.totalBytesWritten;
let bytesTotal = data.totalBytesExpectedToWrite;
let progress = data.progress;

console.log( "upload progress: " + progress + "%");
});
}
Expand All @@ -53,30 +88,32 @@ doUpload(){
{
name: 'file[]',
filename: 'image2.gif',
filepath: "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7",
filepath: "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7", // base64 only support ios
filetype: 'image/gif',
},
];

let opts = {
url: 'http://my.server/api/upload',
files: files,
method: 'POST', // optional: POST or PUT
headers: { 'Accept': 'application/json' }, // optional
params: { 'user_id': 1 }, // optional
files: files,
method: 'POST', // optional: POST or PUT, only support ios, android always have POST
headers: { 'Accept': 'application/json' }, // optional, only support ios, android always have { 'Accept': 'application/json' }
params: { 'user_id': 1 }, // optional, Android support this only string. If you want this in Android use params: { 'user_id': '1' }
};

RNUploader.upload( opts, (err, response) => {
if( err ){
console.log(err);
return;
}

let status = response.status;
let responseString = response.data;
let json = JSON.parse( responseString );

console.log('upload complete with status ' + status);

// android's response is response.body.string.
});
}

Expand All @@ -90,17 +127,19 @@ doUpload(){
||type|required|description|example|
|---|---|---|---|---|
|`url`|string|required|URL to upload to|`http://my.server/api/upload`|
|`method`|string|optional|HTTP method, values: [PUT,POST], default: POST|`POST`|
|`headers`|object|optional|HTTP headers|`{ 'Accept': 'application/json' }`|
|`params`|object|optional|Query parameters|`{ 'user_id': 1 }`|
|`method(only iOS)`|string|optional|HTTP method, values: [PUT,POST], default: POST|`POST`|
|`headers(only iOS)`|object|optional|HTTP headers|`{ 'Accept': 'application/json' }`|
|`params(iOS)`|object|optional|Query parameters|`{ 'user_id': 1 }`|
|`params(Android)`|object|optional|Query parameters|`{ 'user_id': '1' }`<br> only support string value. You can't use int, boolean, etc..|
|`files`|array|required|Array of file objects to upload. See below.| `[{ name: 'file', filename: 'image1.png', filepath: 'assets-library://...', filetype: 'image/png' } ]` |

`callback` is a method with two parameters:

||type|description|example|
|---|---|---|---|
|error|string|String detailing the error|`A server with the specified hostname could not be found.`|
|response|object{status:Number, data:String}|Object returned with a status code and data.|`{ status: 200, data: '{ success: true }' }`|
|response(iOS)|object{status:Number, data:String}|Object returned with a status code and data.|`{ status: 200, data: '{ success: true }' }`|
|response(Android)|String|String returned with responseBody.|`success: true`|


#### `files`
Expand All @@ -110,23 +149,23 @@ doUpload(){
|---|---|---|---|---|
|name|string|optional|Form parameter key for the specified file. If missing, will use `filename`.|`file[]`|
|filename|string|required|filename|`image1.png`|
|filepath|string|required|File URI<br>Supports `assets-library:`, `data:` and `file:` URIs and file paths.|`assets-library://...`<br>`data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOV...`<br>`file:/tmp/image1.png`<br>`/tmp/image1.png`|
|filepath|string|required|File URI<br>Supports `assets-library:`, `data:` and `file:` URIs and file paths.|`assets-library://...(iOS)`<br>`content://...(Android)`<br>`data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOV...(only iOS)`<br>`file:/tmp/image1.png`<br>`/tmp/image1.png`|
|filetype|string|optional|MIME type of file. If missing, will infer based on the extension in `filepath`.|`image/png`|

### Progress
### Progress (only support iOS)
To monitor upload progress simply subscribe to the `RNUploaderProgress` event using DeviceEventEmitter.

```
DeviceEventEmitter.addListener('RNUploaderProgress', (data)=>{
let bytesWritten = data.totalBytesWritten;
let bytesTotal = data.totalBytesExpectedToWrite;
let progress = data.progress;

console.log( "upload progress: " + progress + "%");
});
```

### Cancel
### Cancel (only support iOS)
To cancel an upload in progress:
```
RNUploader.cancel()
Expand All @@ -143,8 +182,9 @@ Inspired by similiar projects:
* progress reporting
* packaged as a static library
* support for multiple files at a time
* support for files from the assets library, base64 `data:` or `file:` paths
* support for files from the assets library, base64 `data:` or `file:` paths
* no external dependencies (ie: AFNetworking)
* support Android

## License

Expand Down
19 changes: 0 additions & 19 deletions RNUploader/RNUploader.ios.js

This file was deleted.

36 changes: 36 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
buildscript {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}

dependencies {
classpath 'com.android.tools.build:gradle:1.1.3'
}
}

apply plugin: 'com.android.library'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
}

repositories {
maven { url "https://jitpack.io" }
}

dependencies {
compile 'com.android.support:appcompat-v7:23.+'
compile 'com.facebook.react:react-native:0.16.+'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.zhy:okhttputils:2.6.2'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
5 changes: 5 additions & 0 deletions android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<manifest
xmlns:tools="http://schemas.android.com/tools"
package="com.burlap.filetransfer">

</manifest>
Loading