@sharr/dom-upload

1.3.0 • Public • Published

Welcome to @sharr/dom-upload 👋

The sharr.io library for direct uploads from the browser.

Provides two types of JS API:

  • generic JS class
  • React HOC

Install

npm install @sharr/dom-upload

Usage

Prerequisites

Register your account on https://sharr.io - the Upload as a Service platform and obtain the clientToken for your website.

Options

Regardless of the way you use this package, the underlying API is the same, so the options configuration is generally the same.

option required description
clientToken yes clientToken obtained when registering your website/app on https://sharr.io
inputElement optional Reference to DOM <input type="file"> element,
use when you want to allow selecting file from computer or mobile

One of inputElement, dropContainerElement, handlePaste options is required for automation of the upload proces. If none of those options is set, you'll need to manually call setFile(file) method to provide file for upload.
dropContainerElement optional Reference to DOM container, which allows for providing file for upload using drag & drop method
handlePaste optional
default: false
Set true to enable pasting an image from clipboard.
Only one instance of SharrDomUpload with handlePaste set to true can be created on single web page.
autoSubmit optional
default: false
Set true to enable auto-submitting the file after selecting
autoEnable optional
default: true
Set false if you don't want created instance to be instantly active. When set to false, you need to later call enable() method to activate the instance.
onSelect optional A callback to be called when file gets selected. Called with two arguments: (1) a native File object, (2) a native Event object being a source of selecting the file
onSubmit optional A callback to be called when submit is triggered. Called with no arguments
onProgress optional A callback called on upload progress. Called with one arguments: a native ProgressEvent object
onUpload optional A callback to be called on upload successful finish. Called with one argument: upload data object: { id: string, token: string, url: string }
onError optional A callback to be called on upload error. Called with one argument: native Error object

SharrDomUpload API

Class methods:

  • constructor

    Returns new SharrDomUpload instance.

    argument required description
    options optional Options object. If not provided, default options will be used. Options can be also set later using setOptions instance method.

Instance methods:

  • setOptions(options)

    Allows for setting/updating option(s) for already created instance.

    Returns this.

    argument required description
    options yes Options object. Merged with existing instance options, what allows for updating only selection option(s).
  • enable()

    Activates the instance by attaching event listeners.

    Returns this.

  • disable()

    Deactivates the instance (removes attached event listeners).

    Returns this.

  • setFile(file[, source])

    Sets the file to be uploaded. Method called internally when DOM elements are provided in options. If no DOM elements are provided, this method can be called to manually set the file for upload, for example: from your own event listeners or uploading logic.

    Triggers calling onSelect callback.

    If autoSubmit option is set, calling setFile will also trigger submitting the file.

    Returns this.

    argument required description
    file yes Native File object.
    source optional The source event of the file. When called internally by automatic event listeners, this is populated with native Event object
  • async submit()

    Submits the file to the cloud. Automatically called internally if autoSubmit option is set. If not, needs to be called manually, after file has been set.

    Triggers calling onSubmit callback.

    Eventually triggers calling onProgress and onUpload or onError callbacks.

    Throws Error if called before file has been set.

    Returns a Promise that resolves with data also passed to onUpload callback.

Usage type: Import as ES Module in generic JS

import SharrDomUpload from '@sharr/dom-upload';

const inputElement = document.getElementById('file-input');
const dropContainerElement = document.getElementById('drop-container');
const submitButton = document.getElemenById('submit');

const sharr = new SharrDomUpload({
  clientToken: 'your clientToken here',
  inputElement,
  dropContainerElement,
  handlePaste: true,
  autoSubmit: false,
  onSelect: (file) => {
    // e.g.: display file preview here
  },
  onUpload: ({ id, url }) => {
    // e.g.: store file url for later
  }
});

// needed because we set `autoSubmit: false` in options
submitButton.addEventListener('click', () => {
  sharr.submit();
});

Usage type: React HOC

This package provides also convinient HOC to use with your React components.

Here's how to use it:

  • Container file

    import React from 'react';
    import { withSharrUpload } from '@sharr/dom-upload';
    import { UploadComponent } from './UploadComponent';
    
    export function UploadContainer() {
      const SharrUploadComponent = withSharrUpload(UploadComponent);
    
      const onUpload = ({ id, url }) => {
        // your custom logic
      }
    
      return (
        <SharrUploadComponent
          clientToken='you clientToken here'
          onUpload={onUpload}
          autoSubmit
          handlePaste
        />
      );
    }
  • Wrapped Component file

    Your wrapped component will need to handle some of the few specific props passed to it by SharrUpload HOC:

    prop type required description
    onSelect Function optional (*) Call this function to set a file for upload, e.g. as a onChange callback for <input type="file"> element in your component.
    onSubmit Function optional Call this function if you're not using autoSubmit option and you want to submit the file from within wrapped component.
    dropContainerRef React ref optional (*) Use this ref object in your render() method attaching it to the DOM element that you want to be a file drop zone. Use only when you need HOC to automatically handle setting file for upload by drag & drop.
    file Native File object optional This prop is set after the file has been selected for upload
    uploading boolean optional This prop is set to true after submitting the file or to false when upload finishes.
    progress number optional Value between 0 and 1 indicating progress of the upload. Set 1 or multiple times after submitting the file.
    sharrId number optional Sharr ID of the uploaded file, set after upload finishes.
    sharrToken number optional Sharr TOKEN of the uploaded file, set after upload finishes.
    sharrUrl string optional URL to the uploaded file, set after upload finishes.
    error string optional Error message set in case of upload error (like exceeded size limit or network failure)

    (*) - one of onSelect or dropContainerRef must be used for setting the file for upload.

    import React from 'react';
    
    export function UploadComponent({
      file,
      url,
      dropContainerRef,
      onSelect
    }) {
      return (
        <div ref={dropContainerRef}>
          <input type="file" onChange={onSelect}>
          <p>Selected file: {file ? file.name : 'none'}</p>
          <p>File URL: {url}</p>
        </div>
      );
    }

Author

👤 Sharr

Website: https://sharr.io

Package Sidebar

Install

npm i @sharr/dom-upload

Weekly Downloads

1

Version

1.3.0

License

ISC

Unpacked Size

31.1 kB

Total Files

10

Last publish

Collaborators

  • jacekzlowocki