1.3.0 ā€¢ Published 3 years ago

@sharr/dom-upload v1.3.0

Weekly downloads
2
License
ISC
Repository
-
Last release
3 years ago

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.

optionrequireddescription
clientTokenyesclientToken obtained when registering your website/app on https://sharr.io
inputElementoptionalReference 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.
dropContainerElementoptionalReference to DOM container, which allows for providing file for upload using drag & drop method
handlePasteoptionaldefault: falseSet 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.
autoSubmitoptionaldefault: falseSet true to enable auto-submitting the file after selecting
autoEnableoptionaldefault: trueSet 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.
onSelectoptionalA 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
onSubmitoptionalA callback to be called when submit is triggered. Called with no arguments
onProgressoptionalA callback called on upload progress. Called with one arguments: a native ProgressEvent object
onUploadoptionalA callback to be called on upload successful finish. Called with one argument: upload data object: { id: string, token: string, url: string }
onErroroptionalA callback to be called on upload error. Called with one argument: native Error object

SharrDomUpload API

Class methods:

  • constructor

    Returns new SharrDomUpload instance.

    argumentrequireddescription
    optionsoptionalOptions 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.

    argumentrequireddescription
    optionsyesOptions 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.

    argumentrequireddescription
    fileyesNative File object.
    sourceoptionalThe 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:

    proptyperequireddescription
    onSelectFunctionoptional (*)Call this function to set a file for upload, e.g. as a onChange callback for <input type="file"> element in your component.
    onSubmitFunctionoptionalCall this function if you're not using autoSubmit option and you want to submit the file from within wrapped component.
    dropContainerRefReact refoptional (*)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.
    fileNative File objectoptionalThis prop is set after the file has been selected for upload
    uploadingbooleanoptionalThis prop is set to true after submitting the file or to false when upload finishes.
    progressnumberoptionalValue between 0 and 1 indicating progress of the upload. Set 1 or multiple times after submitting the file.
    sharrIdnumberoptionalSharr ID of the uploaded file, set after upload finishes.
    sharrTokennumberoptionalSharr TOKEN of the uploaded file, set after upload finishes.
    sharrUrlstringoptionalURL to the uploaded file, set after upload finishes.
    errorstringoptionalError 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

1.3.0

3 years ago

1.2.3

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago