Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More โ†’
Socket
Sign inDemoInstall
Socket

@bytescale/upload-widget-react

Package Overview
Dependencies
Maintainers
1
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bytescale/upload-widget-react

React File Upload UI Widget โ€” Lightweight & supports: drag and drop, multiple uploads, image cropping, customization & more ๐Ÿš€ Comes with Cloud Storage ๐ŸŒ

  • 4.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3.2K
decreased by-58.71%
Maintainers
1
Weekly downloads
ย 
Created
Source

Bytescale Upload Widget for React

Beautiful File Upload Widget for React
(With Built-in Cloud Storage)



Twitter URL

Get Started โ€” Try on CodePen

Upload Widget Demo

100% Serverless File Upload Widget
Powered by Bytescale


Supports: Image Cropping, Video Previews, Document Previews, Drag & Drop, and more...

Full Documentation โ€ข Headless SDK โ€ข Media Processing APIs โ€ข Storage โ€ข CDN




Installation

Install via NPM:

npm install @bytescale/upload-widget-react

Or via YARN:

yarn add @bytescale/upload-widget-react

Or via a <script> tag:

<script src="https://js.bytescale.com/upload-widget-react/v4"></script>

Usage

UploadButton โ€” Try on CodePen

The UploadButton component uses a render prop to provide an onClick callback to your button element.

When clicked, a file upload modal will appear:

import { UploadButton } from "@bytescale/upload-widget-react";

// Full Configuration:
// https://www.bytescale.com/docs/upload-widget#configuration
const options = {
  apiKey: "free", // Get API keys from: www.bytescale.com
  maxFileCount: 10
};

const MyApp = () => (
  <UploadButton options={options}
                onComplete={files => alert(files.map(x => x.fileUrl).join("\n"))}>
    {({onClick}) =>
      <button onClick={onClick}>
        Upload a file...
      </button>
    }
  </UploadButton>
);

Required props:

  • options
  • children

Optional props:

  • onComplete

UploadDropzone โ€” Try on CodePen

The UploadDropzone component renders an inline drag-and-drop file upload dropzone:

import { UploadDropzone } from "@bytescale/upload-widget-react";

// Full Configuration:
// https://www.bytescale.com/docs/upload-widget#configuration
const options = {
  apiKey: "free", // Get API keys from: www.bytescale.com
  maxFileCount: 10
};

const MyApp = () => (
  <UploadDropzone options={options}
                  onUpdate={files => alert(files.map(x => x.fileUrl).join("\n"))}
                  width="600px"
                  height="375px" />
);

Required props:

  • options

Optional props:

  • onUpdate
  • width
  • height

Result

The callbacks receive a Array<UploadWidgetResult>:

{
  fileUrl: "https://upcdn.io/FW25...",   // URL to use when serving this file.
  filePath: "/uploads/example.jpg",      // File path (we recommend saving this to your database).

  editedFile: undefined,                 // Edited file (for image crops). Same structure as below.

  originalFile: {
    fileUrl: "https://upcdn.io/FW25...", // Uploaded file URL.
    filePath: "/uploads/example.jpg",    // Uploaded file path (relative to your raw file directory).
    accountId: "FW251aX",                // Bytescale account the file was uploaded to.
    originalFileName: "example.jpg",     // Original file name from the user's machine.
    file: { ... },                       // Original DOM file object from the <input> element.
    size: 12345,                         // File size in bytes.
    lastModified: 1663410542397,         // Epoch timestamp of when the file was uploaded or updated.
    mime: "image/jpeg",                  // File MIME type.
    metadata: {
      ...                                // User-provided JSON object.
    },
    tags: [
      "tag1",                            // User-provided & auto-generated tags.
      "tag2",
      ...
    ]
  }
}

โš™๏ธ Configuration

All configuration is optional (except for the apiKey field, which is required).

const options = {
  apiKey: "free",                 // Get API keys from: www.bytescale.com
  locale: myCustomLocale,         // EN_US by default. (See "Localization" section below.)
  maxFileCount: 5,                // Unlimited by default (or 1 if multi: false).
  maxFileSizeBytes: 1024 ** 2,    // Unlimited by default.
  mimeTypes: ["image/*"],         // Unrestricted by default. Supports * wildcard suffix.
  multi: false,                   // False by default.
  onInit: ({                      // Exposes lifecycle methods for the component.
    close,                        // Closes the widget when called.
    reset,                        // Resets the widget when called.
    updateConfig                  // Updates the widget's config by passing a new config
  }) => {},                       // object to the method's first parameter.
  onUpdate: files => {},          // Called each time the list of uploaded files change.
  onPreUpload: async file => ({
    errorMessage: "Uh oh!",       // Displays this validation error to the user (if set).
    transformedFile: file         // Uploads 'transformedFile' instead of 'file' (if set).
  }),
  showFinishButton: true,         // Show/hide the "finish" button in the widget.
  showRemoveButton: true,         // Show/hide the "remove" button next to each file.
  styles: {
    colors: {
      primary: "#377dff",         // Primary buttons & links
      active: "#528fff",          // Primary buttons & links (hover). Inferred if undefined.
      error: "#d23f4d",           // Error messages
      shade100: "#333",           // Standard text
      shade200: "#7a7a7a",        // Secondary button text
      shade300: "#999",           // Secondary button text (hover)
      shade400: "#a5a6a8",        // Welcome text
      shade500: "#d3d3d3",        // Modal close button
      shade600: "#dddddd",        // Border
      shade700: "#f0f0f0",        // Progress indicator background
      shade800: "#f8f8f8",        // File item background
      shade900: "#fff"            // Various (draggable crop buttons, etc.)
    },
    fontFamilies: {
      base: "arial, sans-serif"   // Base font family (comma-delimited).
    },
    fontSizes: {
      base: 16                    // Base font size (px).
    }
  },
  path: {                         // Optional: a string (full file path) or object like so:
    fileName: "Example.jpg",      // Supports path variables (e.g. {ORIGINAL_FILE_EXT}).
    folderPath: "/uploads"        // Please refer to docs for all path variables.
  },
  metadata: {
    hello: "world"                // Arbitrary JSON metadata (saved against the file).
  },
  tags: ["profile_picture"],      // Requires a Bytescale account.
  editor: {
    images: {
      preview: true,              // True by default if cropping is enabled. Previews PDFs and videos too.
      crop: true,                 // True by default.
      cropFilePath: image => {    // Choose the file path used for JSON image crop files.
        const {filePath} = image  // In:  https://www.bytescale.com/docs/upload-api/types/FileDetails
        return `${filePath}.crop` // Out: https://www.bytescale.com/docs/upload-api/types/FilePathDefinition
      },
      cropRatio: 4 / 3,           // Width / Height. Undefined enables freeform (default).
      cropShape: "rect"           // "rect" (default) or "circ".
    }
  },
}

๐Ÿณ๏ธ Localization

Default is EN_US:

const myCustomLocale = {
  "error!": "Error!",
  "done": "Done",
  "addAnotherFile": "Add another file...",
  "addAnotherImage": "Add another image...",
  "cancel": "cancel",
  "cancelInPreviewWindow": "Cancel",
  "cancelled!": "cancelled",
  "continue": "Continue",
  "customValidationFailed": "Failed to validate file.",
  "crop": "Crop",
  "finish": "Finished",
  "finishIcon": true,
  "image": "Image",
  "maxFilesReached": "Maximum number of files:",
  "maxImagesReached": "Maximum number of images:",
  "maxSize": "File size limit:",
  "next": "Next",
  "of": "of",
  "orDragDropFile": "...or drag and drop a file.",
  "orDragDropFiles": "...or drag and drop files.",
  "orDragDropImage": "...or drag and drop an image.",
  "orDragDropImages": "...or drag and drop images.",
  "pleaseWait": "Please wait...",
  "removed!": "removed",
  "remove": "remove",
  "skip": "Skip",
  "unsupportedFileType": "File type not supported.",
  "uploadFile": "Upload a File",
  "uploadFiles": "Upload Files",
  "uploadImage": "Upload an Image",
  "uploadImages": "Upload Images",
  "validatingFile": "Validating file..."
}

๐ŸŒ API Support

๐ŸŒ File Management APIs

Bytescale provides a wide range of File Management APIs:

๐ŸŒ Media Processing APIs (Image/Video/Audio)

Bytescale also provides real-time Media Processing APIs:

Image Processing API (Original Image)

Here's an example using a photo of Chicago:

https://upcdn.io/W142hJk/raw/example/city-landscape.jpg

Image Processing API (Transformed Image)

Using the Image Processing API, you can produce this image:

https://upcdn.io/W142hJk/image/example/city-landscape.jpg
  ?w=900
  &h=600
  &fit=crop
  &f=webp
  &q=80
  &blur=4
  &text=WATERMARK
  &layer-opacity=80
  &blend=overlay
  &layer-rotate=315
  &font-size=100
  &padding=10
  &font-weight=900
  &color=ffffff
  &repeat=true
  &text=Chicago
  &gravity=bottom
  &padding-x=50
  &padding-bottom=20
  &font=/example/fonts/Lobster.ttf
  &color=ffe400

Authorization

Bytescale supports two types of authorization:

API Keys

The Bytescale Upload Widget uses the apiKey parameter to authenticate with the Bytescale API.

With API key auth, the requester has access to the resources available to the API key:

  • Secret API keys (secret_***) have access to all API endpoints (see the Bytescale JavaScript SDK).

  • Public API keys (public_***) have access to file upload, file download, and file listing API endpoints. File overwrites, file deletes, and all other destructive operations cannot be performed using public API keys. File listing is also disabled by default (but can be changed in the API key's settings).

You must always use public API keys (e.g. public_***) in your client-side code.

Each API key can have its read/write access limited to a subset of files/folders.

JWT Cookies

JWT cookies are optional.

With JWT cookies, the user can download private files directly via the URL, as authorization is performed implicitly via a session cookie. This allows the browser to display private files in <img> and <video> elements.

With JWT cookies, the user can also upload files to locations that aren't otherwise permitted by the API key, but are permitted by the JWT's payload. This is because the Bytescale Upload Widget internally uses the Bytescale JavaScript SDK to perform file uploads, and the Bytescale JavaScript SDK automatically injects the user's JWT into all API requests once the AuthManager.beginAuthSession method has been called.

Note: when using JWT cookies to download files, the ?auth=true query parameter must be added to the URL.

Learn more about the AuthManager and JWT cookies ยป

UrlBuilder

The Bytescale JavaScript SDK exports a UrlBuilder to construct URLs from filePath values:

import { UrlBuilder } from "@bytescale/sdk";

Recommended: you should always save filePath values to your DB instead of fileUrl values.

Raw Files

To get the URL for the uploaded image /example.jpg in its original form, use the following:

// Returns: "https://upcdn.io/1234abc/raw/example.jpg"
UrlBuilder.url({
  accountId: "1234abc",
  filePath: "/example.jpg"
});
Images

To resize the uploaded image /example.jpg to 800x600, use the following:

// Returns: "https://upcdn.io/1234abc/image/example.jpg?w=800&h=600"
UrlBuilder.url({
  accountId: "1234abc",
  filePath: "/example.jpg",
  options: {
    transformation: "image",
    transformationParams: {
      w: 800,
      h: 600
    }
  }
});

Image Processing API Docs ยป

Videos

To transcode the uploaded video /example.mov to MP4/H.264 in HD, use the following:

// Returns: "https://upcdn.io/1234abc/video/example.mov?f=mp4-h264&h=1080"
UrlBuilder.url({
  accountId: "1234abc",
  filePath: "/example.mov",
  options: {
    transformation: "video",
    transformationParams: {
      f: "mp4-h264",
      h: 1080
    }
  }
});

Video Processing API Docs ยป

Audio

To transcode the uploaded audio /example.wav to AAC in 192kbps, use the following:

// Returns: "https://upcdn.io/1234abc/audio/example.wav?f=aac&br=192"
UrlBuilder.url({
  accountId: "1234abc",
  filePath: "/example.wav",
  options: {
    transformation: "audio",
    transformationParams: {
      f: "aac",
      br: 192
    }
  }
});

Audio Processing API Docs ยป

Archives

To extract the file document.docx from the uploaded ZIP file /example.zip, use the following:

// Returns: "https://upcdn.io/1234abc/archive/example.zip?m=extract&artifact=/document.docx"
UrlBuilder.url({
  accountId: "1234abc",
  filePath: "/example.zip",
  options: {
    transformation: "archive",
    transformationParams: {
      m: "extract"
    },
    artifact: "/document.docx"
  }
});

Archive Processing API Docs ยป

๐Ÿ™‹ Can I use my own storage?

Bytescale supports AWS S3, Cloudflare R2, Google Storage, DigitalOcean Spaces, and Bytescale Storage.

Bytescale Storage Docs ยป

๐Ÿ‘‹ Create your Bytescale Account

Bytescale is the best way to upload, transform, and serve images, videos, and audio at scale.

Create a Bytescale account ยป

Full Documentation

License

MIT

Keywords

FAQs

Package last updated on 17 Sep 2023

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