Giter VIP home page Giter VIP logo

vydia / react-native-background-upload Goto Github PK

View Code? Open in Web Editor NEW
721.0 26.0 326.0 1.01 MB

Upload files in your React Native app even while it's backgrounded. Supports Android and iOS, including camera roll assets.

License: MIT License

JavaScript 22.76% Java 21.33% Objective-C 18.78% Ruby 2.28% Starlark 0.64% Shell 2.03% Kotlin 19.42% CMake 0.30% C++ 7.74% Objective-C++ 4.72%
react-native android ios file-upload nsurlsession hacktoberfest

react-native-background-upload's Introduction

react-native-background-upload npm version GitHub Actions status GitHub Actions status semantic-release

The only React Native http post file uploader with android and iOS background support. If you are uploading large files like videos, use this so your users can background your app during a long upload.

NOTE: Use major version 4 with RN 47.0 and greater. If you have RN less than 47, use 3.0. To view all available versions: npm show react-native-background-upload versions

Installation

1. Install package

npm install --save react-native-background-upload

or

yarn add react-native-background-upload

Note: if you are installing on React Native < 0.47, use [email protected] instead of react-native-background-upload

2. Link Native Code

Autolinking (React Native >= 0.60)

iOS

cd ./ios && pod install && cd ../

Android
ProGuard

Add this to your ProGuard configuration (proguard-rules.pro) :

-keep class net.gotev.uploadservice.** { *; }

Automatic Native Library Linking (React Native < 0.60)

react-native link react-native-background-upload

Or, Manually Link It

iOS

  1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...>
  2. Go to node_modulesreact-native-background-uploadios ➜ select VydiaRNFileUploader.xcodeproj
  3. Add VydiaRNFileUploader.a to Build Phases -> Link Binary With Libraries

Android

  1. Add the following lines to android/settings.gradle:

    include ':react-native-background-upload'
    project(':react-native-background-upload').projectDir = new File(settingsDir, '../node_modules/react-native-background-upload/android')
  2. Add the compile and resolutionStrategy line to the dependencies in android/app/build.gradle:

    configurations.all { resolutionStrategy.force 'com.squareup.okhttp3:okhttp:3.4.1' } // required by react-native-background-upload until React Native supports okhttp >= okhttp 3.5
    
    dependencies {
        compile project(':react-native-background-upload')
    }
  3. Add the import and link the package in MainApplication.java:

    import com.vydia.RNUploader.UploaderReactPackage;  <-- add this import
    
    public class MainApplication extends Application implements ReactApplication {
        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                new MainReactPackage(),
                new UploaderReactPackage() // <-- add this line
            );
        }
    }
  4. Ensure Android SDK versions. Open your app's android/app/build.gradle file. Ensure compileSdkVersion and targetSdkVersion are 25. Otherwise you'll get compilation errors.

3. Expo

To use this library with Expo one must first detach (eject) the project and follow step 2 instructions. Additionally on iOS there is a must to add a Header Search Path to other dependencies which are managed using Pods. To do so one has to add $(SRCROOT)/../../../ios/Pods/Headers/Public to Header Search Path in VydiaRNFileUploader module using XCode.

Usage

import Upload from 'react-native-background-upload'

const options = {
  url: 'https://myservice.com/path/to/post',
  path: 'file://path/to/file/on/device',
  method: 'POST',
  type: 'raw',
  maxRetries: 2, // set retry count (Android only). Default 2
  headers: {
    'content-type': 'application/octet-stream', // Customize content-type
    'my-custom-header': 's3headervalueorwhateveryouneed'
  },
  // Below are options only supported on Android
  notification: {
    enabled: true
  },
  useUtf8Charset: true
}

Upload.startUpload(options).then((uploadId) => {
  console.log('Upload started')
  Upload.addListener('progress', uploadId, (data) => {
    console.log(`Progress: ${data.progress}%`)
  })
  Upload.addListener('error', uploadId, (data) => {
    console.log(`Error: ${data.error}%`)
  })
  Upload.addListener('cancelled', uploadId, (data) => {
    console.log(`Cancelled!`)
  })
  Upload.addListener('completed', uploadId, (data) => {
    // data includes responseCode: number and responseBody: Object
    console.log('Completed!')
  })
}).catch((err) => {
  console.log('Upload error!', err)
})

Multipart Uploads

Just set the type option to multipart and set the field option. Example:

const options = {
  url: 'https://myservice.com/path/to/post',
  path: 'file://path/to/file%20on%20device.png',
  method: 'POST',
  field: 'uploaded_media',
  type: 'multipart'
}

Note the field property is required for multipart uploads.

API

Top Level Functions

All top-level methods are available as named exports or methods on the default export.

startUpload(options)

The primary method you will use, this starts the upload process.

Returns a promise with the string ID of the upload. Will reject if there is a connection problem, the file doesn't exist, or there is some other problem.

options is an object with following values:

Note: You must provide valid URIs. react-native-background-upload does not escape the values you provide.

Name Type Required Default Description Example
url string Required URL to upload to https://myservice.com/path/to/post
path string Required File path on device file://something/coming/from%20the%20device.png
type 'raw' or 'multipart' Optional raw Primary upload type.
method string Optional POST HTTP method
customUploadId string Optional startUpload returns a Promise that includes the upload ID, which can be used for future status checks. By default, the upload ID is automatically generated. This parameter allows a custom ID to use instead of the default.
headers object Optional HTTP headers { 'Accept': 'application/json' }
field string Required if type: 'multipart' The form field name for the file. Only used when type: 'multipart uploaded-file
parameters object Optional Additional form fields to include in the HTTP request. Only used when type: 'multipart
notification Notification object (see below) Optional Android only. { enabled: true, onProgressTitle: "Uploading...", autoClear: true }
useUtf8Charset boolean Optional Android only. Set to true to use utf-8 as charset.
appGroup string Optional iOS only. App group ID needed for share extensions to be able to properly call the library. See: https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati

Notification Object (Android Only)

Name Type Required Description Example
enabled boolean Optional Enable or diasable notifications. Works only on Android version < 8.0 Oreo. On Android versions >= 8.0 Oreo is required by Google's policy to display a notification when a background service run { enabled: true }
autoClear boolean Optional Autoclear notification on complete { autoclear: true }
notificationChannel string Optional Sets android notificaion channel { notificationChannel: "My-Upload-Service" }
enableRingTone boolean Optional Sets whether or not to enable the notification sound when the upload gets completed with success or error { enableRingTone: true }
onProgressTitle string Optional Sets notification progress title { onProgressTitle: "Uploading" }
onProgressMessage string Optional Sets notification progress message { onProgressMessage: "Uploading new video" }
onCompleteTitle string Optional Sets notification complete title { onCompleteTitle: "Upload finished" }
onCompleteMessage string Optional Sets notification complete message { onCompleteMessage: "Your video has been uploaded" }
onErrorTitle string Optional Sets notification error title { onErrorTitle: "Upload error" }
onErrorMessage string Optional Sets notification error message { onErrorMessage: "An error occured while uploading a video" }
onCancelledTitle string Optional Sets notification cancelled title { onCancelledTitle: "Upload cancelled" }
onCancelledMessage string Optional Sets notification cancelled message { onCancelledMessage: "Video upload was cancelled" }

getFileInfo(path)

Returns some useful information about the file in question. Useful if you want to set a MIME type header.

path is a string, such as file://path.to.the.file.png

Returns a Promise that resolves to an object containing:

Name Type Required Description Example
name string Required The file name within its directory. image2.png
exists boolean Required Is there a file matching this path?
size number If exists File size, in bytes
extension string If exists File extension mov
mimeType string If exists The MIME type for the file. video/mp4

cancelUpload(uploadId)

Cancels an upload.

uploadId is the result of the Promise returned from startUpload

Returns a Promise that resolves to an boolean indicating whether the upload was cancelled.

addListener(eventType, uploadId, listener)

Adds an event listener, possibly confined to a single upload.

eventType Event to listen for. Values: 'progress' | 'error' | 'completed' | 'cancelled'

uploadId The upload ID from startUpload to filter events for. If null, this will include all uploads.

listener Function to call when the event occurs.

Returns an EventSubscription. To remove the listener, call remove() on the EventSubscription.

Events

progress

Event Data

Name Type Required Description
id string Required The ID of the upload.
progress 0-100 Required Percentage completed.

error

Event Data

Name Type Required Description
id string Required The ID of the upload.
error string Required Error message.

completed

Event Data

Name Type Required Description
id string Required The ID of the upload.
responseCode string Required HTTP status code received
responseBody string Required HTTP response body
responseHeaders string Required HTTP response headers (Android)

cancelled

Event Data

Name Type Required Description
id string Required The ID of the upload.

Customizing Android Build Properties

You may want to customize the compileSdk, buildToolsVersion, and targetSdkVersion versions used by this package. For that, add this to android/build.gradle:

ext {
    targetSdkVersion = 23
    compileSdkVersion = 23
    buildToolsVersion = '23.0.2'
}

Add it above allProjects and you're good. Your android/build.gradle might then resemble:

buildscript {
    repositories {
        jcenter()
    }
}

ext {
    targetSdkVersion = 27
    compileSdkVersion = 27
    buildToolsVersion = '23.0.2'
}

allprojects {

FAQs

Is there an example/sandbox app to test out this package?

Yes, there is a simple react native app that comes with an express server where you can see react-native-background-upload in action and try things out in an isolated local environment.

RNBackgroundExample

Does it support iOS camera roll assets?

Yes, as of version 4.3.0.

Does it support multiple file uploads?

Yes and No. It supports multiple concurrent uploads, but only a single upload per request. That should be fine for 90%+ of cases.

Why should I use this file uploader instead of others that I've Googled like react-native-uploader?

This package has two killer features not found anywhere else (as of 12/16/2016). First, it works on both iOS and Android. Others are iOS only. Second, it supports background uploading. This means that users can background your app and the upload will continue. This does not happen with other uploaders.

Contributing

See CONTRIBUTING.md.

Common Issues

BREAKING CHANGE IN 3.0

This is for 3.0 only. This does NOT apply to 4.0, as recent React Native versions have upgraded the okhttp dependencies. Anyway...

In 3.0, you need to add

    configurations.all { resolutionStrategy.force 'com.squareup.okhttp3:okhttp:3.4.1' }

to your app's app's android/app/build.gradle file.

Just add it above (not within) dependencies and you'll be fine.

BREAKING CHANGE IN 2.0

Two big things happened in version 2.0. First, the Android package name had to be changed, as it conflicted with our own internal app. My bad. Second, we updated the android upload service dependency to the latest, but that requires the app have a compileSdkVersion and targetSdkVersion or 25.

To upgrade: In MainApplication.java:

Change

```java
import com.vydia.UploaderReactPackage;
```

to

```java
import com.vydia.RNUploader.UploaderReactPackage;
```

Then open your app's android/app/build.gradle file. Ensure compileSdkVersion and targetSdkVersion are 25.

Done!

Gratitude

Thanks to:

react-native-background-upload's People

Contributors

albinhubsch avatar allinelara avatar apzelos avatar baderserhan avatar dcurletti avatar dependabot[bot] avatar ejohnf avatar kdawgwilk avatar kenleezle avatar maxschmeling avatar michelbahl avatar mookiies avatar morgenhaar avatar nkovacic avatar ovr avatar palid avatar petergaultney avatar pulbyte avatar r0b0t3d avatar reime005 avatar rkretzschmar avatar saalim95 avatar semantic-release-bot avatar sharifhh avatar siiiiilvio avatar stevepotter avatar thatjuan avatar tikitdo avatar tsmmark avatar watadarkstar 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-background-upload's Issues

Path with spaces breaks upload

Hello, it's me again!

First, the "symptoms" of this bug are a bug themselves - it seems whenever react-native-background-upload hits a runtime error, it calls the "Cancelled" event instead of "Error", which provides absolutely no data about what just happened.

The main bug: paths with spaces in them do not work whatsoever. I'm looking into workarounds now and how to escape this in a way that the library can find the file, but am not having success so far.

Here's an example of a pretty "dirty" URI that I would expect to work with this library, but currently is not:

file:///Users/isaachinman/Library/Developer/CoreSimulator/Devices/336A9F2F-F5E7-4DD5-83BB-F40CBD15548D/data/Containers/Data/PluginKitPlugin/958086C1-0339-42F7-922A-7600B4B1C690/tmp/05 - february 2018 (myphotopack.com).jpg

Update: I was able to get this working with a simple encodeURI. Options:

  1. Expect users to provide safe urls, don't encode for them. Provide some kind of helpful feedback instead of failing silently.

  2. Encode path for users.

IOS: Upload with file:// error

Hi there,

I have params on header like this:

var path = "/var/mobile/Containers/Data/Application/Documents/Video.mp4";
var options = {
url : "http://upload.........",
path : 'file://'+path,
method : 'POST',
headers : {
'Accept' : 'application/json'
},
files : [{
name : 'coverFile',
filename : name,
filepath : path,
filetype : 'video/mp4',
}],
}

But I cannot upload correct because the final path is : 'file:///var/mobile/Containers/Data/Application/Documents/Video.mp4’

Any help please ?

Fatal exception. Bad notification for startForeground.

This exception occurs in SDK 27 (Android 8.1) but not in lower SDK versions.

Fatal Exception: android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 groupKey=com.clamber vis=PRIVATE)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6494)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Turning off notifications prevents the exception from occurring.

    const options = {
      // ...
      notification: {
        // Required to prevent 
        enabled: false,
      },
    };

The issue appears to be fairly common and widely document for other libraries. I believe this is the same issue on SO.

I don't have a reproduction available but I believe there is one in an issue on this other upload library

License type?

Hi, I notice that there is no license in the repo - what's the deal with the use of the package?

Thanks!

Module VydiaRNFileUploader requires main queue setup ...

Module VydiaRNFileUploader requires main queue setup since it overrides initbut doesn't implementrequiresMainQueueSetup. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.`

Error: expected x bytes but received y%

Whenever I try to upload image to my Digital ocean spaces it starts uploading and then restarts again before reaching 100% and after one or two such attempts it throws me an error which looks something like this:
Error: expected 1433 bytes but received 1500%

I am not sure what is going wrong here

I am uploading the image using presigned url using following options

                const options = {
					url: data.url,
					path: uri,
					method: "PUT",
					type: "raw",
					field: "uploaded_media",
					headers: {
						"Content-Type": type,
						"x-amz-acl": "public-read"
					},
					notification: {
						enabled: true
					}
				};

Listeners for backgrounded events

First off, awesome work!

I had a question about the event listeners. Will they fire if the event (progress, error, completion) is an event that happens in the background, when the app isn't running?
If so, will they wake up the app? Or will they just fire the next time the app runs?

Or do they only work if the event fires while the app is running? If that is the case, is there a way to ask for errors or completions that occurred in the background?

Unsupported scheme (Android)

I got the error - only on Android - : Unsupported scheme: file:///storage/emulated/0/Android/data/com.nnn.android.client/files/Pictures/image-9ed429ce-5b06-4f04-816a-c278e5da33d4.jpg

v4.1.0
react-native-cli: 2.0.1
react-native: 0.51.0

const options = { url: url, path: path, method: 'PUT', headers: { JWT: openIdToken, }, // Below are options only supported on Android notification: { enabled: true, }, } Upload.startUpload(options) .then(uploadId => { Upload.addListener('completed', uploadId, data => { resolve() }) }) .catch(e => { sendLog(Cannot upload image ${e}, true) reject(e) })

Anyone with the same issue?

Android can't find file:///storage/emulated

Hi,

On android I have an error when trying to upload a file created with react-native-camera:
Upload error! Error: Could not find file at path: file://storage/emulated/0/Movies/VID_20170202_094146.mp4 the path

Any idea ?

responseBody on IOS

Hello,
I have tried a few workarounds to try and get a response body on IOS but to no avail.
My use case is the server is sending the URL back after the upload as a JSON string.

If anyone has any idea or knows what to do?

I tried to add a didReceiveData:(NSData *)receivedData delegate but no luck.

Cheers,

Package.json Peer Dependencies

Just wanted to point this out... The react-native peer-dependency has caused me some issues installing.

"peerDependencies": {
"react": "*",
"react-native": ">=0.39.0 <0.30.0"
},

401 is calling "completed" event

Just a quick one: in setting up this project in my own app, I noticed that 401 server responses are still triggering the "completed" event. All 4xx responses should presumably call the "error" event, not "completed".

No throttling of upload progress

During upload, many many progress events can be updated, and this can result in a choppy UI. This could be bypassed with some effort on the app side, but really the progress events should be only emitted periodically.

I propose a property progressReportInterval:number, which is the minimum difference in progress % from the previous event. So if you set this to 1, you will only get updates at 1%, 2%, 3%, etc. Set it to 10 and you'll get 10%, 20%... It should accept a range from 0 (disabled) to 100, although I see no practical use for it above 10.

Anyone have ideas here?

Docs regarding linking are misleading

Found this project recently and was really looking forward to using it. I've encountered a really weird issue though that has prevented me from doing so.

To anyone just opening this issue, I'm sure it will seem like a very common import mistake. However, it's not.

I did yarn add react-native-background-upload. Then I just copy/pasted the usage example straight into my application:

import Upload from 'react-native-background-upload'

const options = {
  url: 'https://myservice.com/path/to/post',
  path: 'file://path/to/file/on/device',
  method: 'POST',
  type: 'raw',
  headers: {
    'my-custom-header': 's3headervalueorwhateveryouneed'
  },
  // Below are options only supported on Android
  notification: {
    enabled: true
  }
}

console.log('What is Upload: ', Upload)

Upload.startUpload(options).then((uploadId) => {
  console.log('Upload started')
  Upload.addListener('progress', uploadId, (data) => {
    console.log(`Progress: ${data.progress}%`)
  })
  Upload.addListener('error', uploadId, (data) => {
    console.log(`Error: ${data.error}%`)
  })
  Upload.addListener('cancelled', uploadId, (data) => {
    console.log(`Cancelled!`)
  })
  Upload.addListener('completed', uploadId, (data) => {
    // data includes responseCode: number and responseBody: Object
    console.log('Completed!')
  })
}).catch((err) => {
  console.log('Upload error!', err)
})

Here's what I see when this runs:

screen shot 2018-03-26 at 17 48 14

Really don't understand this. You can see the output of the console log directly before the function invocation, and Upload is clearly an object with several methods on it, startUpload being the first one.

This is probably a more general RN problem (?), but I'm not at all sure where to start. Any ideas?

Video uploads larger than ~100MB fail on iOS

I keep running into this issue on iOS when uploading a video. Videos of any size longer than about 100mb consistently fail, with the message "Lost connection to background transfer service". Under that size they seem to work fine, but larger files fail before getting to the progress phase.

React Native 0.40+

A change in RN 0.40 makes bridges backwards incompatible. We will be upgrading to RN 0.40 at some point in the next month or two and will likely upgrade this package. It has to happen. At that point we'll do a major version bump.

I ask everyone: what version of RN are you on? Do you plan to upgrade, and if so, when?

No Test Project

It would be great to see a test project for this package. Right now everyone is testing on different backends and apps.

The app will simply let you choose and upload a file.

The backend can be a basic Express app that has a single route for uploading a file. It can just save the file to /tmp.

Any ideas here before I implement it?

[Help wanted] Convert to file:// path

Hi,

It is specified in the README that we can only upload files with a path starting with file://.

I'm using react-native-camera to record a video that I want to upload and the path returned starts with assets-library:// on iOS. I've been searching but I haven't found any way to convert this path to a file:// path.

I come from cordova and I used to call resolveLocalFileSystemURL(assetLibraryFilePath) to get the file:// but I can't seem to find an equivalent in react-native :(

Any help please ?

Upload error! Error: NSInvalidArgumentException

Hi! I am trying to convert from an iOS camera roll asset to the file asset format of "file://.."

An image uri would be:
"assets-library://asset/asset.JPG?id=A19B54F5-367B-4992-B647-AF7705338124&ext=JPG"

I then use RNFetchBlob.wrap() and gets:
"RNFetchBlob-file://assets-library://asset/asset.JPG?id=BF29BC40-EBAB-43FD-A451-B2AC21842DD8&ext=JPG"

That didn't work so I sliced out the "RNFetchBlob-" part to make it "file://..." and that didn't work either. I get the error:
"Upload error! Error: NSInvalidArgumentException"

How do I convert in the right way?

[Android] Progress listener not receiving any progress

Hi, thanks for the library.
I've managed to make it work on iOS but having trouble using the same code in android

This is how I implement the upload code

doUpload = () => {
    var path = _.cloneDeep(this.props.source)
    const options = {
      url: `${AppConfig.baseUrl}v1/media/upload/image`,
      path: Platform.OS === 'ios' ? path : path.replace('file://', ''),
      method: 'POST',
      field: 'file',
      type: 'multipart',
      headers: {
        Authorization: `Token ${this.props.token}`
      },
      // Below are options only supported on Android
      notification: {
        enabled: false
      }
    }

    Upload.startUpload(options)
      .then(uploadId => {
        console.tron.log('Upload started')
        Upload.addListener('progress', uploadId, data => {
          this.setState({
            progress: Math.floor(data.progress)
          })
          // console.tron.log(`Progress: ${data.progress}%`)
        })
        Upload.addListener('error', uploadId, data => {
          console.tron.error(data)
          console.tron.log(`Error: ${data.error}%`)
        })
        Upload.addListener('cancelled', uploadId, data => {
          console.tron.log(`Cancelled!`)
        })
        Upload.addListener('completed', uploadId, data => {
          // data includes responseCode: number and responseBody: Object
          console.tron.log(data)
          console.tron.log('Completed!' + uploadId)
          this.props.uploadFileSuccess(JSON.parse(data.responseBody))
        })
      })
      .catch(err => {
        console.tron.log('Upload error!', err)
      })
};

Environment

  • RN 0.51
  • React 16.0.0

Progress listener not working on android.

Really need help

Events are not fired on Android

Hi, I need to upload files to Amazon S3 in my app.
Everything works fine on the iOS, but I have some troubles with Android.

Here is the example

Upload.startUpload({
        url: upload_url,
        method: 'PUT',
        path: Platform.OS === 'ios' ? path : path.replace('file://', ''),
        headers: {
          'Content-Type': mimeType,
          'Content-Length': size + '',
        },
}).then(uploadId => {
        Upload.addListener('progress', uploadId, console.log);
        Upload.addListener('error', uploadId, console.log);
        Upload.addListener('cancelled', uploadId, console.log);
        Upload.addListener('completed', uploadId, console.log);
}).catch(err => {
        console.log('Upload error!', err);
});

For some reason, none of the progress, error, canceled and completed events are not fired after the upload starts. I get an uploadId and nothing happens after that.

I've tried manipulating the SDKs versions (from this issue as well), upgrading React Native to the latest release, scanning the adb logcat. I've even put logs in the library's Java startUpload method, but everything seems to be fine. Do you have any idea what could go wrong? Perhaps your library has conflicts with another lib?

React Native version: 0.52.0
react-native-background-upload version: 4.4.0
Devices: OnePlus 5 with Android 8 and 8.1, Google Pixel 2XL emulator with Android 7.x

Error "Unfortunately, `app` has stopped"

Adding react-native-background-upload to my project causes breaking issue in android. When the app opens a modal pops up with the error Unfortunately, app has stopped. I tried running the app on multiple different android phones including an android simulator. The crash is caused by the runtime error Could not invoke WebSocketModule.connect at com.facebook.react.bridge.JavaMethodWrapper.invoke

Here is the stack trace:
screen shot 2018-03-12 at 12 33 01 pm

react-native version: 0.53.0
react-native-background-upload version: 4.4.0.

app/build.gradle

dependencies {
    compile project(':react-native-background-upload')
    compile project(':react-native-sensitive-info')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"
    compile project(':react-native-navigation')
    compile project(':mapbox-react-native-mapbox-gl')
}

// required by react-native-background-upload until React Native supports okhttp >= okhttp 3.5
configurations.all { resolutionStrategy.force 'com.squareup.okhttp3:okhttp:3.4.1' }

MainApplication.java

    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new UploaderReactPackage(),
            new RNSensitiveInfoPackage(),
          new RCTMGLPackage()
        );
    }

settings.gradle

include ':react-native-background-upload'
project(':react-native-background-upload').projectDir = new File(settingsDir, '../node_modules/react-native-background-upload/android')
include ':react-native-sensitive-info'
project(':react-native-sensitive-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sensitive-info/android')

include ':app'

include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/android/app/')

include ':mapbox-react-native-mapbox-gl'
project(':mapbox-react-native-mapbox-gl').projectDir = new File(rootProject.projectDir, '../node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl')

The compileSDKVersion is "26.0.1" and the targetSDKVersion is "26".

how can i pass list of images as input this library.

I want upload list images to the server, but using your library I can only pass single image at a time.
I can also call this library API multiple times using a loop or something. But the problem is when my app goes in background, it will only upload the current image which is in the upload process, it is not initiating further uploads.
So is there any way by which I can pass all list of images as input to your library and it will handle rest of all

Complications with POST request

Hello,

My colleagues and I are trying to upload videos with react-native-background-upload, but although we can see the progression of the file being uploaded, our API receives a request without the video file or any body.

Does your library supports sending requests with body? Is there a way to send a request with the videos on body instead of using path? Which key can we use to retrieve the video file on our API, if we’re adding the video file via ‘path’.

We are using react-native version 0.44.0 and testing on an iPhone device

Our options:

const uploadOptions = {
    url: REQUEST_URL,
    path: video.uri, 
    method: 'POST',
    headers: {
        ‘key’: ‘value’,
    },
    body: formData,
}

method does not override or implement a method from a supertype

node_modules\react-native-background-upload\android\src\main\java\com\vydia\UploaderReactPackage.java:23: error: method does not override or implement a method from a supertype
@OverRide
^
3 errors
Incremental compilation of 1 classes completed in 0.556 secs.
:react-native-background-upload:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

assets-library support

Im new to object-c and RN. I really wish that assets-library:// can be supported in the upcoming version. I did some research and it came up with some discussions and here about how to do that in cordova but havent get anything from RN. While ALAssetsLibrary is deprecated in xcode 8 and above. Check out this repo for the full support.

build.gradle issue

In our project we are pointing to latest compileSdkVersion 27.0.0 as it is latest. But as the react-native-background is using 25 we are getting build issues. As we are using other packages too using latest sdk versions, we cant degrade to 25, could you please upgrade sdk version to latest sdk version.

Issue uploading file: IOS + Android

Hi,

I just upgraded to 3.0.0-beta and now the files doesn't seems to get to the server.
If I use in the headers 'Content-Type': 'x-www-form-urlencoded', or nothing at all, the data does not get to the server, although the component shows the progress and completion correctly.
If I add 'Content-Type': 'multipart/form-data' to headers, then I get an error on the server:
Unexpected error while processing request: invalid byte sequence in UTF-8.
I use Ruby on Rails and the service was tested successfully with a standard multipart form in html.
Any idea?
Anyone has a reference implementation of server which is actually working, to test the component?
Thanks!

Chunked uploads

Are there any plans to implement chunked uploads? My site runs through Cloudflare, so uploads are restricted to 100MB in size. I've worked around this with the website uploads by using chunked uploads, so that only a few megabytes are sent in each chunk. It also allows the file to be resumed.

Android Application force close when add/link component

I got error after link/add this component to my project, my app always force close when it active. i have no idea with the error, because no error log found. i attach a screenshoot.

my step :

and i'm not even use the component in my code.
then it try to create new project and it work fine, buat why if i use this in my old project i got that error. is there any dependecy in this componet, or maybe it have conflict with other component ?

Screenshot_1484194737.png

thanks

Upload method

hi i want ask something, what method used in this upload scheme.? is it only and default using POST method.? how if i want use PUT method.?

thanks.

How to listen to bytesWritten, and totalbytesExpectedToWrite?

Are those events being sent?

// for IOS, register event listeners or else they don't fire on DeviceEventEmitter
if (NativeModules.VydiaRNFileUploader) {
  NativeModule.addListener(eventPrefix + 'progress')
  NativeModule.addListener(eventPrefix + 'error')
  NativeModule.addListener(eventPrefix + 'completed')
  **
  NativeModule.addListener(eventPrefix + 'bytesWritten')
  NativeModule.addListener(eventPrefix + 'totalBytesExpectedToWrite')
  **
}

Cannot Read Property 'startUpload' of undefined

screenshot at jan 30 18-51-44

Trying to upload a video with two more parameters

Details:-
"react": "16.2.0",
"react-native": "0.52.0",
"react-native-background-upload": "^4.1.0",

 uploadVideo =()=>{
     let formData = new FormData();
       formData.append("host_id", "79********");
       formData.append("file_type", 1);
       formData.append("hostfiles", {
            name: this.state.fileName,
            uri: this.state.videoFile.path,
       });


const options = {
  url: "https://Demo******.com:6021/user/api/host/uploadfiles",
  path: this.state.videoFile.path,
  method: 'POST',
  field:formData,
  headers: {
    'Content-Type': 'multipart/form-data',
     'Accept': 'application/json'
  },
  type: 'multipart'
};

Upload.startUpload(options).then((uploadId) => {
   console.log('Upload started')
   Upload.addListener('progress', uploadId, (data) => {
     console.log(`Progress: ${data.progress}%`)
   })
   Upload.addListener('error', uploadId, (data) => {
     console.log(`Error: ${data.error}%`)
   })
   Upload.addListener('completed', uploadId, (data) => {
     console.log('Completed!')
   })
   }).catch((err) => {
      console.log('Upload error!', err)
  });
}

How to upload to S3 bucket?

Hi,
Is there a way to upload to S3 bucket?

I tried it like this and got the following error:

const options = {
    url: 'https://s3.amazonaws.com/mybucketname',
    method: 'POST',
    path: uri, // /Users/user/Library/.../5D94544E-E33B-475E-BB3F-5BFA72E15A63.jpg
    type: 'multipart',
    headers: {
    },
    field: 'uploaded_media',
    region: "us-east-1",
    accessKey: 'myaccesskey',
    secretKey: "mysecretkey",
    // Below are options only supported on Android
    notification: {
      enabled: true
    }
  };

  Upload.startUpload(options).then((uploadId) => {
    console.log('Upload started');
    Upload.addListener('progress', uploadId, (data) => {
      console.log(`Progress: ${data.progress}%`)
    });
    Upload.addListener('error', uploadId, (data) => {
      console.log(`Error: ${data.error}%`)
    });
    Upload.addListener('cancelled', uploadId, (data) => {
      console.log(`Cancelled!`)
    });
    Upload.addListener('completed', uploadId, (data) => {
      console.log('Completed!', data)
    })
  }).catch((err) => {
    console.log('Upload error!', err)
  });

and i got this error:

{id: "9", responseCode: 400, responseBody: "<?xml version="1.0" encoding="UTF-8"?>↵<Error><Cod…lyaNSBlMomTWSgYgOloDwFtOReU01RA=</HostId></Error>"}
id
:
"9"
responseBody
:
"<?xml version="1.0" encoding="UTF-8"?>↵<Error><Code>MaxPostPreDataLengthExceeded</Code><Message>Your POST request fields preceeding the upload file was too large.</Message><MaxPostPreDataLengthBytes>20480</MaxPostPreDataLengthBytes><RequestId>83B08A26C8A163F4</RequestId><HostId>EKI1mI93HBz1uQIdo+gk4aTATLawDTb/hUYGvR/JNtDilyaNSBlMomTWSgYgOloDwFtOReU01RA=</HostId></Error>"
responseCode
:
400

Base64 support ?

Hey, Thanks for this great library, works perfectly. I just wanted to ask if this will work with base64 string ?

Thanks

Response Body is Empty

The responseBody is "" (empty) as shown below:

 Object {
  "id": "1cbc0a24-6c08-420d-80ae-69ea0fe04312",
  "responseBody": "",
  "responseCode": 201,
}

My code:

const headers: BlobHeaders = {
    "x-ms-blob-type": BLOB_TYPE,
    "x-ms-date": date,
    "Content-Type": contentType,
    "Content-Disposition": `attachment; filename="${uuid}"`,
    Authorization
  };

const options = {
      url,
      path: dest,
      method: "PUT",
      type: "raw",
      headers,
      // Below are options only supported on Android
      notification: {
        enabled: true
      }
    };

const uploadId = await Upload.startUpload(options);

Upload.addListener("progress", uploadId, data => {
      console.log(`Progress: ${data.progress}%`);
});
Upload.addListener("error", uploadId, data => {
      console.log(`Error: ${data.error}%`);
});
Upload.addListener("cancelled", uploadId, data => {
      console.log(`Cancelled!`);
});
Upload.addListener("completed", uploadId, data => {
      // data includes responseCode: number and responseBody: Object
      console.log("Completed!", data);
});

Seems like a bug in this library but maybe the server isn't returning a responseBody.

content-type header missing on Android

Not sure if this is specific to an Android version, but on a OnePlus 3 running Android 8.0.0, the upload request hits my API without a content-type header set. The header is set correctly on iOS.

As a workaround, I've explicitly set the header in my options object:

const options = {
  url: 'https://myapi/add-photo',
  path: image.uri,
  method: 'POST',
  type: 'raw',
  headers: {
    'content-type': 'application/octet-stream',
  },
  // Android-only options
  notification: {
    enabled: true,
  },
}

Let me know if you need more info to debug.

Unable to build on Android with RN 0.45.1: AAPT: Error retrieving parent for item:

On android with react native 0.45.1 this library can't be build and throws the following errors:

./android/app/build/intermediates/res/merged/debug/values-v24/values-v24.xml:3: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

./android/app/build/intermediates/res/merged/debug/values-v24/values-v24.xml:4: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

./android/app/build/intermediates/res/merged/debug/values-v24/values-v24.xml:3: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

./android/app/build/intermediates/res/merged/debug/values-v24/values-v24.xml:4: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

Steps to reproduce:

react-native init test --version [email protected]
cd test
yarn add react-native-background-upload
react-native link
cd android && ./gradlew assembleDebug

With react-native 0.42 this is not an issue.

Some hints about it: i am not that familiar with android native but from some people i've heard that it can have do something with buildToolsVersion.

Android Application Error Response Code 413

Hi, its me again..
I'm trying your component, and i got this error log

Screen Shot 2017-01-13 at 12.57.53 AM.png

it say, error response code 413. I think thats error from my server. But when i use post man and other react upload method (i try step from this link https://github.com/g6ling/React-Native-Tips/tree/master/How_to_upload_photo%2Cfile_in%20react-native) no error found.

am i miss something ?

btw my code look like this.

const options = {
    url: 'http://test.exsample.com/api/file_upload.php',
    path: this.state.file_path,
    headers: {
      'my-custom-header': "s3headervalueorwhateveryouneed"
    }
  }
  console.log(options.path)
  Upload.startUpload(options).then((uploadId) => {
    console.log('Upload started')
    Upload.addListener('progress',uploadId, (data) => {
      console.log(`Progress: ${data.progress}%`)
    })
    Upload.addListener('error',uploadId, (data) => {
      console.log(`Error: ${data.error}`)
    })
    Upload.addListener('completed',uploadId, (data) => {
      console.log("response Code : "+data.responseCode)
      console.log("response Body : "+data.responseBody)
      console.log(`Completed!`)
    })
  }).catch(function(err) {
    console.log('Upload error!',err)
  });

thanks again

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.