React-Uploady

repository·master·Indexed 22 days ago

https://github.com/rpldy/react-uploady

A lightweight, modular library for building client-side file-upload features in React. It provides a foundation for uploading files with customizable components, hooks, and support for various protocols including TUS and chunked uploads. The ecosystem includes specialized packages such as @rpldy/abort for cancelling uploads, @rpldy/chunked-sender for splitting files, @rpldy/retry for failed upload recovery, and @rpldy/mock-sender for testing.

Tokens
46.1K
Snippets
98
Records
249
Agent score
78%

What's inside React-Uploady

  1. Overview of React-Uploady packages

    master

    React-Uploady is a modular library. You can install only the pieces you need to keep your bundle size small.

    Main Packages

    • @rpldy/uploader: The core processing and queuing engine.
    • @rpldy/uploady: The React context provider and hooks.

    UI Packages

    • @rpldy/upload-button: Upload button component and asUploadButton HOC.
    • @rpldy/upload-preview: Image and video preview component.
    • @rpldy/upload-url-input: Input component for sending URLs as upload info.
    • @rpldy/upload-drop-zone: Drag & drop zone for files and folders.
    • @rpldy/upload-paste: Paste-to-upload functionality.
    • @rpldy/retry-hooks: Hooks for interacting with the retry mechanism.

    Providers

    • @rpldy/chunked-uploady: Wrapper for Uploady with chunked upload support.
    • @rpldy/tus-uploady: Wrapper for Uploady with TUS (resumable) upload support.
    • @rpldy/native-uploady: Uploady for React Native (no react-dom).

    Senders

    • @rpldy/sender: Main XHR file sender.
    • @rpldy/chunked-sender: Adds chunked upload support to the XHR Sender.
    • @rpldy/tus-sender: Adds TUS resumable upload support.
    • @rpldy/mock-sender: Mock sender for testing.

    Extras

    • @rpldy/retry: Adds support for retrying failed uploads.
  2. Overview of @rpldy/uploady

    master

    The @rpldy/uploady package is the core UI component of the React Uploady ecosystem. Its primary roles are:

    1. Initialization: It initializes and exposes the underlying uploader functionality.
    2. Provider: It contains the Provider component, which acts as the context provider that all other UI packages (like progress bars, upload lists, etc.) rely on to access upload state and logic.
    3. Advanced Features: It provides multiple hooks that allow client applications to access advanced features and upload data.
  3. What is @rpldy/raw-uploader?

    master

    The @rpldy/raw-uploader package is intended to be the base uploader for the React Uploady ecosystem. It is designed for scenarios where standard functionality (like xhr-sender or abort capabilities) is not required, or when you need to replace the core uploading logic with completely custom functionality.

    Note: As of the current version, this is a placeholder package containing only Flow types and will be expanded in future updates.

  4. Use UploadDropZone to initiate uploads

    master

    The UploadDropZone component is a container that initiates file and folder uploads via drag-and-drop. It supports individual files and recursive directory uploads using html-dir-content.

    Drop Zones can use configuration overrides that supersede the options passed to the parent Uploady component. Note that some options (like those influencing the file input directly, e.g., _multiple_) cannot be overridden.

    import Uploady from "@rpldy/uploady";
    import UploadDropZone from "@rpldy/upload-drop-zone";
    
    const App = () => (
        <Uploady destination={destination}>
            <UploadDropZone onDragOverClassName="drag-over"
                            grouped
                            maxGroupSize={3}
            >
                <span>Drag&Drop File(s) Here</span>            
            </UploadDropZone>
        </Uploady>);
  5. Use Feature Detection with TUS

    master

    When featureDetection is enabled, the sender queries the server for supported extensions. If an option is requested that the server does not support, it will be automatically disabled.

    Supported options subject to feature detection:

    • parallel (requires concatenation extension)
    • sendDataOnCreate (requires creation-with-upload extension)
    • deferLength (requires creation-defer-length extension)

    If you provide an onFeaturesDetected callback, you are responsible for returning an object that merges with the current options to override unsupported features.

    CORS Requirement: For feature detection to work across different origins, the server must allow the Tus-Extension and Tus-Version headers to be read over CORS.

  6. Use Enhancers to modify uploader behavior

    master

    Enhancers are functions used to modify an uploader instance. They are passed as part of the options to the Uploady instance and are applied when the uploader instance is created. They can be used to change how the uploader operates or to provide different default behaviors.

    (uploader: UploaderType, trigger: Trigger<mixed>) => UploaderType
  7. How @rpldy/chunked-sender works

    master

    The @rpldy/chunked-sender adds chunked upload capabilities on top of the regular XHR @rpldy/sender. It provides an UploaderEnhancer that replaces the default send method used by the uploader.

    Limitations:

    • Chunked uploading does not support grouped uploads (sending multiple files in a single XHR request).
    • Chunked uploading does not support URL uploading.

    If these unsupported features are used, the library will fall back to the default @rpldy/sender behavior.

  8. Understand Normal vs. Fast Abort flows

    master

    The @rpldy/abort package provides two different flows for cancelling uploads, determined by the number of pending/active uploads relative to a fastAbortThreshold parameter.

    Threshold Logic

    • If the number of pending/active uploads is less than the fastAbortThreshold (or if the threshold is set to 0), the Normal flow is used.
    • If the number of pending/active uploads is equal to or larger than the fastAbortThreshold, the Fast flow is used.
    • All Abort: The threshold is compared against the total number of pending/active items.
    • Batch Abort: The threshold is compared against the number of pending/active items in the specific batch.
    • Note: Finished items are ignored in these comparisons.

    Normal Abort Flow

    Every item (whether currently uploading or still pending) is individually aborted.

    • An ITEM_ABORT event is fired for every item.
    • For an 'Abort All' operation, a BATCH_ABORT event is also fired.

    Fast Abort Flow

    Only active uploads are cancelled. This is optimized for performance when many items are queued.

    • Pending items are ignored and simply removed from the queue by the uploader.
    • No ITEM_ABORT events are fired for pending items.
    • For an 'Abort All' operation, no BATCH_ABORT event is fired.
  9. Use NativeUploady in React Native

    master

    The NativeUploady component acts as a Provider that initializes and exposes the uploader functionality. It is the foundation for all other UI packages and hooks in a React Native environment.

    Key Differences from web-based Uploady:

    • It does not use react-dom.
    • It does not create a file input element. Instead, you must trigger uploads manually (e.g., using a document picker) and pass the files to the uploader.
    • Props related to file inputs (such as multiple or accept) are not supported because there is no native HTML file input.

    To use hooks or UI components, you must wrap your application (or the relevant part of it) with <NativeUploady /> to provide the UploadyContext.

    import React, { useCallback } from "react";
    import { View, Button } from "react-native";
    import DocumentPicker from "react-native-document-picker/index";
    import NativeUploady from "@rpldy/native-uploady";
    
    const Upload = () => {
    
      const pickFile = useCallback(async () => {
          const res = await DocumentPicker.pick({
            type: [DocumentPicker.types.images],
          });
    
          uploadyContext.upload(res);
      }, [uploadyContext]);
    
        return <View>
                   <Button title="Upload File" onPress={pickFile} />
              </View>;
    };
    
    const App = () => (<NativeUploady    
        grouped
        maxGroupSize={2}
        method="PUT"
        destination={{url: "https://my-server", headers: {"x-custom": "123"}}}>
        
        <Upload/>
        <RestOfMyApp/>
    </NativeUploady>)
  10. How the Uploader works

    master

    The Uploader is a vanilla JavaScript processing and queuing engine. It represents each file as a Batch Item and groups them into Batches. While it is largely internal to the React-Uploady ecosystem, it manages the lifecycle of uploads by firing Batch and BatchItem events.

    Note: If you are building a React application, you should generally use @rpldy/uploady instead of interacting with this package directly, as Uploady handles initialization and event registration for you.

  11. Understand Upload Options and Destination

    master

    Upload Options

    Upload Options configure the uploader's behavior (e.g., whether files can be grouped in a single request). They are typically passed to the <Uploady> instance but can be overridden via:

    • Props passed to an upload button.
    • Dynamic parameters during upload processing.

    Destination

    A Destination is an object within the upload options that configures the server endpoint. At a minimum, it must contain a url property representing the server endpoint.