Giter VIP home page Giter VIP logo

rossmartin / react-native-use-file-upload Goto Github PK

View Code? Open in Web Editor NEW
69.0 4.0 4.0 2.07 MB

A hook for uploading files using multipart form data with React Native.

License: MIT License

JavaScript 3.49% Ruby 3.39% Starlark 1.24% Java 32.49% CMake 0.59% C++ 15.09% Swift 0.13% C 0.21% Objective-C 4.97% Objective-C++ 9.20% TypeScript 29.20%
file-upload react-native photo-upload photo-uploader photo-uploads file-uploader file upload

react-native-use-file-upload's Introduction

react-native-use-file-upload

A hook for uploading files using multipart form data with React Native. Provides a simple way to track upload progress, abort an upload, and handle timeouts. Written in TypeScript and no dependencies required.

npm version

example app

Installation

yarn add react-native-use-file-upload

Example App

There is an example app in this repo as shown in the above gif. It is located within example and there is a small node server script within example/server here. You can start the node server within example using yarn server.

Usage

import useFileUpload, { UploadItem } from 'react-native-use-file-upload';

// Used in optional type parameter for useFileUpload
interface Item extends UploadItem {
  progress?: number;
}

// ...
const [data, setData] = useState<Item[]>([]);
// The generic type param below for useFileUpload is optional
// and defaults to UploadItem. It should inherit UploadItem.
const { startUpload, abortUpload } = useFileUpload<Item>({
  url: 'https://example.com/upload',
  field: 'file',
  // Below options are optional
  method: 'POST',
  data,
  headers,
  timeout: 60 * 1000, // 60 seconds
  onProgress,
  onDone,
  onError,
  onTimeout,
});

const onPressUpload = async () => {
  const promises = data.map((item) => startUpload(item));
  // Use Promise.all instead if you want to throw an error from a timeout or error.
  // As of October 2022 you have to polyfill allSettled in React Native.
  const result = await Promise.allSettled(promises);
};

Methods

startUpload

Start a file upload for a given file. Returns a promise that resolves with OnDoneData or rejects with OnErrorData.

// Objects passed to startUpload should have the below shape at least (UploadItem type)
startUpload({
  name: 'file.jpg',
  type: 'image/jpg',
  uri: 'file://some-local-file.jpg',
});

abortUpload

Abort a file upload for a given file. The promise from startUpload gets rejected and onError runs if present.

// Pass the uri of a file that started uploading
abortUpload('file://some-local-file.jpg');

Options

Name Type Required Description
url string Required The URL to send the request to.
field string Required The field name that will be used for the file in FormData.
method string Optional The HTTP method for the request. Defaults to "POST".
data object Optional An object of additional FormData fields to be set with the request.
headers Headers Optional Option for passsing in requst headers.
const headers = new Headers();
headers.append('Authorization', 'foo');
useFileUpload({ headers });
timeout number Optional The timeout value for the request in milliseconds.
onProgress function Optional Callback when a request times out for a given file. It receives 1 argument of this shape -
// OnProgressData type
{
  item: UploadItem; // or a type that inherits UploadItem
  event: ProgressEvent;
};
// event is the XMLHttpRequest progress event object and it's shape is -
{
  loaded: number,
  total: number
}
onDone function Optional Callback on request completion for a given file. It receives 1 argument of this shape -
// OnDoneData type
{
  item: UploadItem; // or a type that inherits UploadItem
  responseBody: string; // eg "{\"foo\":\"baz\"}" (JSON) or "foo"
  responseHeaders: string;
}
onError function Optional Callback when a request error happens for a given file. It receives 1 argument of this shape -
// onErrorData type
{
  item: UploadItem; // or a type that inherits UploadItem
  error: string;
}
onTimeout function Optional Callback when a request error happens for a given file. It receives 1 argument of this shape -
// OnErrorData type
{
  item: UploadItem; // or a type that inherits UploadItem
  error: string;
  timeout: boolean; // true here
}

FAQs

Do requests continue when the app is backgrounded?

Requests continue when the app is backgrounded on android but they do not on iOS. This can be addressed by using react-native-background-upload.

The React Native team did a heavy lift to polyfill and bridge XMLHttpRequest to the native side for us. There is an open PR in React Native to allow network requests to run in the background for iOS. react-native-background-upload is great but if backgrounding can be supported without any external native dependencies it is a win for everyone.

How can I throttle the file uploads so that I can simulate a real world scenario where upload progress takes time?

You can throttle the file uploads by using ngrok and Network Link Conditioner. Once you have ngrok installed you can start a HTTP tunnel forwarding to the local node server on port 8080 via:

ngrok http 8080

ngrok will generate a forwarding URL to the local node server and you should set this as the url for useFileUpload. This will make your device/simulator make the requests against the ngrok forwarding URL.

You can throttle your connection using Network Link Conditioner if needed. The existing Wifi profile with a 33 Mbps upload works well and you can add a custom profile also. If your upload speed is faster than 100 Mbps you'll see a difference by throttling with Network Link Conditioner. You might not need to throttle with Network Link Conditioner depending on your connection upload speed.

Why send 1 file at a time instead of multiple in a single request?

It is possible to to send multiple files in 1 request. There are downsides to this approach though and the main one is that it is slower. A client has the ability to handle multiple server connections simultaneously, allowing the files to stream in parallel. This folds the upload time over on itself.

Another downside is fault tolerance. By splitting the files into separate requests, this strategy allows for a file upload to fail in isolation. If the connection fails for the request, or the file is invalidated by the server, or any other reason, that file upload will fail by itself and won't affect any of the other uploads.

Why is type and name required in the UploadItem type?

This is because of how React Native abstracts away setting the content-disposition request header for us in their polyfill for FormData. You can see here how that is being done in the getParts function.

License

MIT


Made with create-react-native-library

react-native-use-file-upload's People

Contributors

rastapasta avatar rossmartin 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

Watchers

 avatar  avatar  avatar  avatar

react-native-use-file-upload's Issues

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.