Code Monkey home page Code Monkey logo

react-native-uploader's Introduction

react-native-uploader

A React Native module for uploading files and camera roll assets in Android and iOS. Supports progress notification.

Note

This module is a cover of https://github.com/g6ling/react-native-uploader. I cover it to make it suitable for my project. And I see it useful and share it.

Thanks to @g6ling for great module.

Install

Use rnpm

  1. npm install https://github.com/tranquangvu/react-native-uploader.git --save
  2. rnpm link react-native-uploader

If you don't want use rnpm, do this

iOS

  • npm install https://github.com/tranquangvu/react-native-uploader.git --save
  • In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  • Go to node_modulesreact-native-uploaderios and add RNUploader.xcodeproj
  • In XCode, in the project navigator, select your project. Add libRNUploader.a to your project's Build PhasesLink Binary With Libraries
  • Run your project (Cmd+R)

Android

  • Add to your android/settings.gradle:
include ':react-native-uploader'
project(':react-native-uploader').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-uploader/android')
  • Add to your android/app/build.gradle:
dependencies {
  ...
  compile project(':react-native-uploader')
}
  • Add to MainApplication.java
import com.burlap.filetransfer.FileTransferPackage;
...
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
  ....
  @Override
  protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
      ...
      new FileTransferPackage()
    );
  }
}

Example

This is a simple demo for upload image. It can be run both Android and iOs. See it in https://github.com/tranquangvu/react-native-uploader-demo

Usage

var RNUploader = require('react-native-uploader');

var {
	StyleSheet, 
	Component,
	View,
	DeviceEventEmitter,
} = React;
componentDidMount(){
	// upload progress
	DeviceEventEmitter.addListener('RNUploaderProgress', (data)=>{
	  let bytesWritten = data.totalBytesWritten;
	  let bytesTotal   = data.totalBytesExpectedToWrite;
	  let progress     = data.progress;
	  
	  console.log( "upload progress: " + progress + "%");
	});
}
doUpload(){
	let files = [
		{
			name: 'file[]',
			filename: 'image1.png',
			filepath: 'assets-library://....',  // image from camera roll/assets library
			filetype: 'image/png',
		},
		{
			name: 'file[]',
			filename: 'image2.gif',
			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, 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.
	});
}

API

RNUploader.upload( options, callback )

options is an object with values:

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(iOS) object optional Query parameters { 'user_id': 1 }
params(Android) object optional Query parameters { 'user_id': '1' }
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(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

files is an array of objects with values:

type required description example
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
Supports assets-library:, data: and file: URIs and file paths.
assets-library://...(iOS)
content://...(Android)
data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOV...(only iOS)
file:/tmp/image1.png
/tmp/image1.png
filetype string optional MIME type of file. If missing, will infer based on the extension in filepath. image/png

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 (only support iOS)

To cancel an upload in progress:

RNUploader.cancel()

Notes

Inspired by similiar projects:

...with noteable enhancements:

  • uploads are performed asynchronously on the native side
  • 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
  • no external dependencies (ie: AFNetworking)
  • support Android

License

MIT

react-native-uploader's People

Contributors

benfwz avatar tranquangvu avatar ulentini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-uploader's Issues

<Android> Upload error

Hi,
I am using react-native-uploader, it works on iOS, but in Android getting

undefined is not an object (evaluating 'b.upload')

Any clue please.

hi why not npm install ?

first, thanks your module ^^;

when npm installed , error occured.

==> npm install https://github.com/tranquangvu/react-native-uploader.git --save

ERR! not fount:git

...
error git clone --template=C:\Users\leesy\AppData\Roaming\npm-cache_git-remotes_templates --mirror https://github.com/tranquangvu/react-native-uploader.git C:\Users\leesy\AppData\Roaming\npm-cache_git-remotes\git-https-github-com-tranquangvu-react-native-uploader-git-4298aac2: undefined
23 error git clone --template=C:\Users\leesy\AppData\Roaming\npm-cache_git-remotes_templates --mirror https://github.com/tranquangvu/react-native-uploader.git C:\Users\leesy\AppData\Roaming\npm-cache_git-remotes\git-https-github-com-tranquangvu-react-native-uploader-git-4298aac2: undefined
24 silly fetchPackageMetaData Error: not found: git
24 silly fetchPackageMetaData at F (C:\Program Files\nodejs\node_modules\npm\node_modules\which\which.js:63:19)
24 silly fetchPackageMetaData at E (C:\Program Files\nodejs\node_modules\npm\node_modules\which\which.js:72:29)
24 silly fetchPackageMetaData at C:\Program Files\nodejs\node_modules\npm\node_modules\which\which.js:81:16
24 silly fetchPackageMetaData at C:\Program Files\nodejs\node_modules\npm\node_modules\which\node_modules\isexe\index.js:44:5
24 silly fetchPackageMetaData at C:\Program Files\nodejs\node_modules\npm\node_modules\which\node_modules\isexe\windows.js:29:5
24 silly fetchPackageMetaData at FSReqWrap.oncomplete (fs.js:117:15)
24 silly fetchPackageMetaData error for https://github.com/tranquangvu/react-native-uploader.git { Error: not found: git
24 silly fetchPackageMetaData at F (C:\Program Files\nodejs\node_modules\npm\node_modules\which\which.js:63:19)
24 silly fetchPackageMetaData at E (C:\Program Files\nodejs\node_modules\npm\node_modules\which\which.js:72:29)
24 silly fetchPackageMetaData at C:\Program Files\nodejs\node_modules\npm\node_modules\which\which.js:81:16
24 silly fetchPackageMetaData at C:\Program Files\nodejs\node_modules\npm\node_modules\which\node_modules\isexe\index.js:44:5
24 silly fetchPackageMetaData at C:\Program Files\nodejs\node_modules\npm\node_modules\which\node_modules\isexe\windows.js:29:5
24 silly fetchPackageMetaData at FSReqWrap.oncomplete (fs.js:117:15) code: 'ENOGIT' }
25 silly rollbackFailedOptional Starting
26 silly rollbackFailedOptional Finishing
...

could you help me ?

(ps. but, git clone well done ^^;)

No error, but not upload in android

1

hi all, I have problem for android I config and run demo => ios work well but android not work, It's not show error => but I checked It not post my api please advise many thanks

localhost server I see 200 but no file uploaded in real

I used https://github.com/jeanpan/react-native-camera-roll-picker to show camera roll and pick images from camera roll, camera roll outputs me image details as per filename: "IMG_0005.JPG" and fileuri: assets-library://asset/asset.JPG?id=ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext=JPG, it does not upload a photo with these details, I was trying to use localhost on xcode and I see 200 status OK but no file in the folder , Plus I found let json = JSON.parse( responseString ); return Json 0 error to crash app. which I commented out .

doUpload(){
console.log("clicked");
let files = [
{
name: 'file[]',
filename: 'IMG_0005.JPG',
filepath: 'assets-library://asset/asset.JPG?id=ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext=JPG', // image from camera roll/assets library
filetype: 'image/jpg',
}
];
let opts = {
url: 'http://localhost:8888/photos',
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.
});
}

error when run-android

Hello,I got this errors,Could you help me?
FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':app'.

    Cannot evaluate module RNFileTransfer : Configuration with name 'default' not found.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.