Coder Social home page Coder Social logo

react-native-uploader's Introduction

react-native-uploader

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

Install

iOS

  1. npm install react-native-uploader --save

  2. Link the native modules:

If you're using React-Native >= 0.29:

  • Link the library with the command react-native link

If you're using React-Native < 0.29:

  • Install rnpm using the command npm install -g rnpm
  • Link the library with the command rnpm link

If you have any issues, you can install the library manually:

  • In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  • Go to node_modulesreact-native-uploaderRNUploader 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
  1. Run your project (Cmd+R)

Example

See ./examples/UploadFromCameraRoll

Example

Usage

import React, { Component } from 'react';

import {
  StyleSheet,
  Component,
  View,
  DeviceEventEmitter,
} from 'react-native';

var RNUploader = NativeModules.RNUploader;
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",
			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
	};

	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);
	});
}

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 object optional Query parameters { 'user_id': 1 }
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 }' }

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://...
data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOV...
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

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

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)

License

MIT

react-native-uploader's People

Contributors

aroth avatar bouchertommy avatar hypatiah avatar polacekpavel avatar rgoldiez avatar

Stargazers

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

Watchers

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

react-native-uploader's Issues

Proposal to merge with our uploader package

@aroth, I had intended to write you over email but there wasn't one visible on your github profile. I'm one of the authors of https://github.com/Vydia/react-native-background-upload. It's similar to yours and adds a few other features, like Android support and uploading while the app is backgrounded (using NSUrlSession on iOS).

I admire your great work on this package and I'd like to propose merging our packages. My motivation is purely to serve the React Native community. If someone wants file upload support, they shouldn't have to evaluate 4 uploader packages. There should be 1 or 2 clear choices and they can install the package and move on with their day. Also, merging the packages will bring more users to each of us, resulting in higher quality code.

Please let me know if you are interested in this. If so, we can discuss the details. You can reply in this thread or to the email in my github profile. Thanks so much!

Binary uploads

Hi. I'm need to upload binary data to a server, (rather than a form post with multipartformdata body). I need the body to just be a stream of bytes. Does plugin this support that type of http body?

Video upload support

Is it possible to upload videos with this plugin? If not, that would be VERY desirable in my book.

If you can upload video already, could we add some documentation so that people know how to do it?

How do you deal with multiple upload events

I'm trying to understand how it would work if the upload action is for multiple files but these actions happen in parallel (one file at a time). How do I identify for which file the upload progress is and how do I cancel an individual upload

Callback not found

Sometimes I got callback error when I use for-loop with RNUploader.upload() (because I need each file has their own progress).
Error msg like that: Invariant Violation: Callback with id 343: RNUploader.upload() not found.

BTW, thanks for this cool plugin! 🍺

Response

Was hoping someone could tell me whether I can get the s3 url back in the response? Trying to post to an api-based chat...so I'd like to get the s3 url back and then post a message to that api that includes the s3 url. I'm using the s3 url on the web-based version of the chat and ideally it would work similarly on iOS. Thanks in advance.

Build fails after adding to project (iOS)

Steps to reproduce:

  • yarn add react-native-uploader
  • react-native link react-native-uploader
  • clean project in xcode
  • rebuild project in xcode

RCTBridgeModule.h:58:3: Typedef redefinition with different types ('struct (anonymous struct at RCTBridgeModule.h:54:16)' vs 'struct RCTMethodInfo') . -- I chopped out my file locations from error

react-native 0.50.3
MacOS High Sierra
Xcode Version 9.2 (9C40b)

Help with multipart upload

First let me say that this component is great. I was able to upload an image (user profile pic) to salesforce.com. However, I'm struggling to figure out how to compose a multipart POST request. Salesforce has a number of examples here. The particular one I'm interested in is below.

How do I use react-native-uploader to send this request?

POST /services/data/v35.0/chatter/feed-elements HTTP/1.1
Authorization: OAuth 00DRR0000000N0g!...
User-Agent: Jakarta Commons-HttpClient/3.0.1
Host: instance_name
Content-Length: 845
Content-Type: multipart/form-data; boundary=a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Accept: application/json

--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Disposition: form-data; name="json"
Content-Type: application/json; charset=UTF-8

{
   "body":{
      "messageSegments":[
         {
            "type":"Text",
            "text":"Please accept this receipt."
         }
      ]
   },
   "capabilities":{
      "content":{
         "description":"Receipt for expenses",
         "title":"receipt.pdf"
      }
   },
   "feedElementType":"FeedItem",
   "subjectId":"005RR000000DmOb"
}

--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Disposition: form-data; name="feedElementFileUpload"; filename="receipt.pdf"
Content-Type: application/octet-stream; charset=ISO-8859-1

...contents of receipt.pdf...

--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq--

Clarification on what is required server-side

What API endpoint is required server-side to manage the other side of this upload? Does it have to manage streaming? How does it have to feed back progress? Could we have a sample in, say, PHP?

It doesn't add React to import part.

My app gets an error to build because RNUploader.m file contains following lines.
import "RCTBridgeModule.h"
import "RCTEventDispatcher"
import "RCTLog.h"

So I change it like this and it does work.
import <React/RCTBridgeModule.h>
import <React/RCTEventDispatcher.h>
import <React/RCTLog.h>

But I want this automatically when I do react-native link.
Anyone could help me?

what would it take to be able to provide nested objects for params?

I'm essentially looking to be able to POST complex JSON.stringified objects. Looking at the objective C code there is a "todo" to add support for objects. I'm no expert in objective-C, I can't even tell if it supports anything but strings, i.e. numbers. What would it take to make the params parameter similar to what you would pass for the body parameter in fetch, or perhaps the non-stringified version as that seems to be its direction?

How does this plugin work?

I have a series of questions, please kindly answer them all.

  1. What if I have different multiple components uses the upload? How does it know the progress of each?

  2. The same thing with multiple components and usage of upload. Using cancel(), how does it know which to cancel?

Android compatibility

Hi!

This project is Android compatible or no? Someone is working in an android version??

Best

Chunked upload support

Does react-native-uploaders support chunked uploads?

(Examining the code makes me think not.)

Upload directly from Camera instead of Camera Roll

If I want my users to open camera from within my react native app, record a short video, preview the video, then upload to server/cloud (so app user never sees/interacts with the cameraRoll), is this possible using your plug-in?

Cancel upload

As title, is there any way to cancel/abort upload?

how to perform resumable upload?

I'm using the Youtube API to upload videos and they have a resumable feature where basically you specify the starting point in bytes from the start of the file when you want to resume. How would we implement that with this package? It seems to only do send all the bytes of the file.

audio file

Hello, can i upload music wav file and what should i put in filetype field 'music/wav' ?

Android: NativeModules.FileTransfer does not exist

Related to #13

I'm on RN 0.32 and your module gives me "Cannot call upload of undefined" because NativeModules.FileTransfer does not exist.

Your module seems to depend on NativeModules.FileTransfer, but this does not exist for me (I console.log it out and it's NULL)

Android support

Hi guys,

Any plans to support this awesome package on android?

Thanks,

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.