Skip to content
JavaScript library for work with Uploadcare Upload API
TypeScript JavaScript
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github/workflows chore: update github actions (#164) Jan 13, 2020
browser-test chore: configurate browser tests (#123) Dec 23, 2019
mock-server
src chore: release v1.0.1 (#169) Jan 14, 2020
test
.editorconfig bootstrap project May 24, 2018
.eslintignore
.eslintrc.json Remove custom rules and use default config for prettier Dec 11, 2019
.gitignore feat: add build step, configure browser field in package.json (#110) Dec 19, 2019
.npmignore Add config json to npm ignore Dec 27, 2018
.prettierrc.js Use prettier-config-standard Dec 11, 2019
.size-snapshot.json
.travis.yml chore: run linter in ci (#148) Dec 26, 2019
AUTHORS.txt New release: v1.0.0.alpha Dec 28, 2018
CHANGELOG.md chore: release v1.0.1 (#169) Jan 14, 2020
LICENSE Fix year and company name in license Feb 7, 2019
README.md Update changelog&readme Dec 20, 2019
package-lock.json chore(deps): update dependency shipjs to v0.14.1 Jan 24, 2020
package.json chore(deps): update dependency shipjs to v0.14.1 Jan 24, 2020
renovate.json test: inc delay (#149) Dec 26, 2019
rollup.config.js Update karma.config.js and remove @uploadcare/release-it Sep 12, 2019
ship.config.js run prodution tests (#163) Jan 9, 2020
tsconfig.build.json feat: add build step, configure browser field in package.json (#110) Dec 19, 2019
tsconfig.json test: fix mock server and use it in tests (#131) Dec 25, 2019

README.md

Uploadcare Upload Client

This is an Uploadcare Upload API wrapper to work with Node.js and browser.

Build Status NPM version GitHub release  Uploadcare stack on StackShare

Install

npm install @uploadcare/upload-client --save

Usage

High-Level API

To access the High-Level API, you need to create an instance of UploadClient providing the necessary settings. Specifying YOUR_PUBLIC_KEY is mandatory: it points to the specific Uploadcare project:

import UploadClient from '@uploadcare/upload-client'

const client = new UploadClient({ publicKey: 'YOUR_PUBLIC_KEY' })

Once the UploadClient instance is created, you can start using the wrapper to upload files from binary data:

const fileUpload = client.uploadFile(fileData)

fileUpload.then(file => console.log(file.uuid))

Another option is uploading files from URL, via the uploadFile method:

const fileURL = 'https://example.com/file.jpg'
const fileUpload = client.uploadFile(fileURL)

fileUpload.then(file => console.log(file.uuid))

You can also use the uploadFile method to get previously uploaded files via their UUIDs:

const fileUUID = 'edfdf045-34c0-4087-bbdd-e3834921f890'
const fileUpload = client.uploadFile(fileUUID)

fileUpload.then(file => console.log(file.uuid))

You can track uploading progress:

const fileUUID = 'edfdf045-34c0-4087-bbdd-e3834921f890'
const onProgress = ({ value }) => {
  console.log(value)
}
const fileUpload = client.uploadFile(fileUUID, { onProgress })

fileUpload.then(file => console.log(file.uuid))

You can cancel file uploading and track this event:

const fileUUID = 'edfdf045-34c0-4087-bbdd-e3834921f890'
const cancelController = new CancelController()
const fileUpload = client.uploadFile(fileUUID, { cancel: cancelController })

fileUpload
  .then(file => console.log(file.uuid))
  .catch(error => {
    if (error.isCancel) {
      console.log(`File uploading was canceled.`)
    }
  })

// Cancel uploading
cancelController.cancel()

List of all available UploadClient API methods:

interface UploadClient {
  updateSettings(newSettings: Settings = {}): void

  getSettings(): Settings

  base(
    file: NodeFile | BrowserFile,
    options: BaseOptions
  ): Promise<BaseResponse>

  info(uuid: Uuid, options: InfoOptions): Promise<FileInfo>

  fromUrl(sourceUrl: Url, options: FromUrlOptions): Promise<FromUrlResponse>

  fromUrlStatus(
    token: Token,
    options: FromUrlStatusOptions
  ): Promise<FromUrlStatusResponse>

  group(uuids: Uuid[], options: GroupOptions): Promise<GroupInfo>

  groupInfo(id: GroupId, options: GroupInfoOptions): Promise<GroupInfo>

  multipartStart(
    size: number,
    options: MultipartStartOptions
  ): Promise<MultipartStartResponse>

  multipartUpload(
    part: Buffer | Blob,
    url: MultipartPart,
    options: MultipartUploadOptions
  ): Promise<MultipartUploadResponse>

  multipartComplete(
    uuid: Uuid,
    options: MultipartCompleteOptions
  ): Promise<FileInfo>

  uploadFile(
    data: NodeFile | BrowserFile | Url | Uuid,
    options: FileFromOptions
  ): Promise<UploadcareFile>

  uploadFileGroup(
    data: (NodeFile | BrowserFile)[] | Url[] | Uuid[],
    options: FileFromOptions & GroupFromOptions
  ): Promise<UploadcareGroup>
}

Low-Level API

Also, you can use low-level wrappers to call the API endpoints directly:

import { base, CancelController } from '@uploadcare/upload-client'

const onProgress = ({ value }) => console.log(value)
const cancelController = new CancelController()
const directUpload = base(fileData, { onProgress, cancel: cancelController }) // fileData must be `Blob` or `File` or `Buffer`

directUpload
  .then(data => console.log(data.file))
  .catch(error => {
    if (error.isCancel) {
      console.log(`File uploading was canceled.`)
    }
  })

// Also you can cancel upload:
cancelController.cancel()

List of all available API methods:

base(
  file: NodeFile | BrowserFile,
  options: BaseOptions
): Promise<BaseResponse>
info(uuid: Uuid, options: InfoOptions): Promise<FileInfo>
fromUrl(sourceUrl: Url, options: FromUrlOptions): Promise<FromUrlResponse>
fromUrlStatus(
  token: Token,
  options: FromUrlStatusOptions
): Promise<FromUrlStatusResponse>
  group(uuids: Uuid[], options: GroupOptions): Promise<GroupInfo>
  groupInfo(id: GroupId, options: GroupInfoOptions): Promise<GroupInfo>
multipartStart(
  size: number,
  options: MultipartStartOptions
): Promise<MultipartStartResponse>
multipartUpload(
  part: Buffer | Blob,
  url: MultipartPart,
  options: MultipartUploadOptions
): Promise<MultipartUploadResponse>
multipartComplete(
  uuid: Uuid,
  options: MultipartCompleteOptions
): Promise<FileInfo>
multipart(
  file: File | Buffer | Blob,
  options: MultipartOptions
): Promise<FileInfo>

Settings

publicKey: string

The main use of a publicKey is to identify a target project for your uploads. It is required when using Upload API.

baseCDN: string

Defines your schema and CDN domain. Can be changed to one of the predefined values (https://ucarecdn.com/) or your custom CNAME.

Defaults to https://ucarecdn.com/.

baseURL: string

API base URL.

Defaults to https://upload.uploadcare.com

fileName: string

You can specify an original filename.

Defaults to original.

store: boolean

Forces files uploaded with UploadClient to be stored or not. For instance, you might want to turn this off when automatic file storing is enabled in your project, but you do not want to store files uploaded with a particular instance.

secureSignature: string

In case you enable signed uploads for your project, you’d need to provide the client with secureSignature and secureExpire params.

The secureSignature is an MD5 hex-encoded hash from a concatenation of API secret key and secureExpire.

secureExpire: string

Stands for the Unix time to which the signature is valid, e.g., 1454902434.

integration: string

X-UC-User-Agent header value.

Defaults to UploadcareUploadClient/${version}/${publicKey} (JavaScript${integration})

checkForUrlDuplicates: boolean

Runs the duplicate check and provides the immediate-download behavior.

saveUrlForRecurrentUploads: boolean

Provides the save/update URL behavior. The parameter can be used if you believe that the sourceUrl will be used more than once. Using the parameter also updates an existing reference with a new sourceUrl content.

source: string

Defines the upload source to use, can be set to local, url, etc.

jsonpCallback: string

Sets the name of your JSONP callback function to create files group from a set of files by using their UUIDs.

pollingTimeoutMilliseconds: number

Internally, Upload Client implements polling to ensure that a file is available on CDN or has finished uploading from URL.

Defaults to 10000 milliseconds (10 seconds).

maxContentLength: number

maxContentLength defines the maximum allowed size (in bytes) of the HTTP response content.

Defaults to 52428800 bytes (50 MB).

retryThrottledRequestMaxTimes: number

Sets the maximum number of attempts to retry throttled requests.

Defaults to 1.

multipartChunkSize: number

This option is only applicable when handling local files. Sets the multipart chunk size.

Defaults to 5242880 bytes (5 MB).

multipartMinFileSize: number

This option is only applicable when handling local files. Sets the multipart uploading file size threshold: larger files will be uploaded in the Multipart mode rather than via Direct Upload. The value is limited to the range from 10485760 (10 MB) to 104857600 (100 MB).

Defaults to 26214400 (25 MB).

multipartMinLastPartSize: number

This option is only applicable when handling local files. Set the minimum size of the last multipart part.

Defaults to 1048576 bytes (1 MB).

maxConcurrentRequests: number

Allows specifying the number of concurrent requests.

Defaults to 4.

contentType: string

This setting is needed for correct multipart uploads.

Defaults to application/octet-stream.

Testing

npm run test

By default, the testing environment is production, but you can run tests with the local environment. It requires starting a mock server.

To start a mock server, you need to execute the following:

npm run mock:start

And then you can run:

NODE_ENV=development npm run test

Security issues

If you think you ran into something in Uploadcare libraries that might have security implications, please hit us up at bugbounty@uploadcare.com or Hackerone.

We'll contact you personally in a short time to fix an issue through co-op and prior to any public disclosure.

Feedback

Issues and PRs are welcome. You can provide your feedback or drop us a support request at hello@uploadcare.com.

You can’t perform that action at this time.