New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-native-use-file-upload

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

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.

  • 0.1.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
156
increased by57.58%
Maintainers
1
Weekly downloads
 
Created
Source

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. The upload route in the node server intentionally throttles the upload requests. You can read more about this in the FAQs below.

Usage

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

// ...
const [data, setData] = useState<UploadItem[]>([]);
const { startUpload, abortUpload } = useFileUpload({
  url: 'https://example.com/upload',
  field: 'file',
  // Below options are optional
  method: 'POST',
  headers,
  timeout: 45000,
  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 (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

NameTypeRequiredDescription
urlstringRequiredThe URL to send the request to.
fieldstringRequiredThe field name that will be used for the file in FormData.
methodstringOptionalThe HTTP method for the request. Defaults to "POST".
headersHeadersOptionalOption for passsing in requst headers.
const headers = new Headers();
headers.append('Authorization', 'foo');
useFileUpload({ headers });
timeoutnumberOptionalThe timeout value for the request in milliseconds.
onProgressfunctionOptionalCallback when a request times out for a given file. It receives 1 argument of this shape -
// OnProgressData type
{
  item: UploadItem;
  event: ProgressEvent<EventTarget>;
};
// event is the XMLHttpRequest progress event object and it's shape is -
{
  loaded: number,
  total: number
}
onDonefunctionOptionalCallback on request completion for a given file. It receives 1 argument of this shape -
// OnDoneData type
{
  item: UploadItem;
  responseBody: string; // eg "{\"foo\":\"baz\"}" (JSON) or "foo"
  responseHeaders: string;
}
onErrorfunctionOptionalCallback when a request error happens for a given file. It receives 1 argument of this shape -
// onErrorData type
{
  item: UploadItem;
  error: string;
}
onTimeoutfunctionOptionalCallback when a request error happens for a given file. It receives 1 argument of this shape -
// OnErrorData type
{
  item: UploadItem;
  error: string;
  timeout: boolean; // true here
}

FAQs

Do requests continue when the app is backgrounded?

Requests will time out if you background the app. This can be addressed by using react-native-background-upload.

The React Native team did a 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. There are plans to have a similar PR for Android as well. react-native-background-upload is great but if backgrounding can be supported without any native dependencies it is a win for everyone.

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.

How does the local node server throttle the upload requests?

The local node server throttles the upload requests to simulate a real world scenario on a cellular connection or slower network. This helps test out the progress and timeout handling on the client. It does this by using the node-throttle library. See the /upload route in here for the details.

How do I bypass the throttling on the local node server?

Set the url in useFileUpload to http://localhost:8080/_upload.

The onDone and promise from startUpload take awhile to resolve in the example app.

This is because of the throttling and can be bypassed.

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

Keywords

FAQs

Package last updated on 09 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc