Qiniu JavaScript SDK

repository·master·Indexed 23 days ago

https://github.com/qiniu/js-sdk

A client-side library for web applications to upload files directly to Qiniu Cloud Storage and perform image processing. Version 3.4.4 supports direct uploads for files < 4MB and chunked uploads with breakpoint resumption for larger files. It includes capabilities for local image compression via qiniu.compressImage and image manipulation through qiniu.pipeline, including thumbnails (imageView2), advanced processing (imageMogr2), EXIF metadata retrieval, and watermarking.

Tokens
7.1K
Snippets
12
Records
47
Agent score
78%

What's inside qiniu-js-sdk

  1. Overview of Qiniu-JavaScript-SDK

    master

    Qiniu-JavaScript-SDK is a frontend JavaScript SDK built on top of the official Qiniu Cloud Storage APIs. It is designed for browsers like IE11, Edge, Chrome, Firefox, and Safari.

    Key Capabilities:

    • File Uploading: Supports direct upload for files < 4MB and chunked upload for files > 4MB. Chunked uploading supports breakpoint resumption (resuming interrupted uploads).
    • Image Data Processing: Provides client-side capabilities for image manipulation including:
      • imageView2: Thumbnails.
      • imageMogr2: Advanced processing (scaling, cropping, rotation, etc.).
      • imageInfo: Retrieve basic image information.
      • exif: Retrieve EXIF metadata.
      • watermark: Add text or image watermarks.
      • pipeline: Chain multiple processing operations together.

    Important Security Note: This is a client-side SDK and does not include logic for generating tokens. For security reasons, you must fetch a token from your backend server. The SDK relies on a server-side implementation to issue these tokens.

  2. Install Qiniu-JavaScript-SDK

    master

    You can integrate the SDK into your project using one of the following three methods:

    1. Using a CDN (Static File)

    Include the script via a <script> tag in your HTML. This will create a global qiniu object.

    2. Using NPM

    Install the package via npm and import it into your module.

    3. Building from Source

    Clone the repository, install dependencies, and run the build command to generate qiniu.min.js in the dist directory.

    # NPM Installation
    npm install qiniu-js
    // NPM Usage
    const qiniu = require('qiniu-js')
    // or
    import * as qiniu from 'qiniu-js'
    # Build from source
    git clone git@github.com:qiniu/js-sdk.git
    cd js-sdk
    npm install
    npm run build
  3. How the upload manager selection works

    master

    The createUploadManager factory automatically selects the appropriate upload strategy based on the file size and configuration:

    1. Force Direct Mode: If options.config.forceDirect is set to true, the Direct manager is used regardless of file size.
    2. Resumable Upload: If the file size is greater than 4 * MB, the Resume manager is used to support chunked/resumable uploads.
    3. Direct Upload: If the file size is less than or equal to 4 * MB (and forceDirect is not enabled), the Direct manager is used.
  4. Configure upload behavior with config object

    master

    The config object passed to qiniu.upload allows fine-tuning of the upload process. Key options include:

    • useCdnDomain: (boolean, default true) Whether to use CDN acceleration domains.
    • region: Select the upload region using qiniu.region constants (e.g., qiniu.region.z2 for South China).
    • retryCount: (number, default 3) Total number of automatic retries.
    • concurrentRequestLimit: (number, default 3) Number of concurrent chunk uploads.
    • chunkSize: (number, default 4 MB) Size of each chunk for multipart uploads.
    • checkByMD5: (boolean, default false) Enables MD5 verification during breakpoint resumption.
    • checkByServer: (boolean, default true) Enables server-side file signature verification.
    • uphost: (string | string[]) Custom upload hosts.
    • upprotocol: (string, default 'https') Custom protocol (http or https).
    • debugLogLevel: ('INFO' | 'WARN' | 'ERROR' | 'OFF') Console logging for debugging.
    const config = {
      useCdnDomain: true,
      region: qiniu.region.z2
    };
  5. Add custom variables and metadata with putExtra

    master

    Use the putExtra object to attach additional information to the uploaded file.

    • fname: The original filename.
    • mimeType: The file type (e.g., 'text/plain').
    • customVars: An object for custom variables. Keys must start with x:.
    • metadata: An object for custom metadata. Keys must start with x-qn-meta-.
    const putExtra = {
      fname: "qiniu.txt",
      mimeType: "text/plain",
      customVars: { 'x:test': 'qiniu' },
      metadata: { 'x-qn-meta': 'qiniu' },
    };
  6. Compress images before uploading

    master

    You can use qiniu.compressImage to reduce the file size of an image before performing the upload. This is useful for saving bandwidth and improving user experience.

    Options for compressImage:

    • quality: Compression quality (e.g., 0.92).
    • noCompressIfLarger: Boolean indicating whether to skip compression if the image is already smaller than a certain threshold.
    • maxWidth (commented out in example): Maximum width for the compressed image.
    • maxHeight (commented out in example): Maximum height for the compressed image.
    const options = {
      quality: 0.92,
      noCompressIfLarger: true
      // maxWidth: 1000,
      // maxHeight: 618
    }
    
    // Compress the image first
    qiniu.compressImage(file, options).then(data => {
      // Use the compressed file (data.dist) for the upload
      const observable = qiniu.upload(data.dist, key, token, putExtra, config)
      const subscription = observable.subscribe(observer) // Upload starts here
    })
  7. Upload files with qiniu.upload()

    master

    The qiniu.upload method is used to upload a file to a Qiniu bucket. It returns an observable object that allows you to monitor the upload progress, handle errors, and detect completion.

    To use it, you must provide a File object, a key (the resource name), and a token (obtained from your backend). You can optionally provide putExtra for custom metadata/variables and config to tune upload behavior like retry counts or chunk sizes.

    To stop an ongoing upload, call .unsubscribe() on the subscription object returned by .subscribe().

  8. Compress images before upload with qiniu.compressImage()

    master

    The qiniu.compressImage method allows you to compress an image locally before uploading it. It supports image/png, image/jpeg, image/bmp, and image/webp.

    Options:

    • quality: (number, 0 to 1) Compression quality. Default is 0.92. Works for jpeg and webp.
    • maxWidth: Maximum width of the output image.
    • maxHeight: Maximum height of the output image.
    • noCompressIfLarger: (boolean) If true, returns the original file if compression would result in a larger file.
  9. Apply image processing via qiniu.pipeline()

    master

    The qiniu.pipeline method allows you to chain multiple image processing operations (watermarking, resizing, cropping, etc.) into a single URL. You pass an array of operation objects (fopArr), the file key, and the domain.

    Supported operations in the array include:

    • watermark: Add image or text watermarks.
    • imageView2: Resizing and thumbnail modes.
    • imageMogr2: Advanced processing like rotation, cropping, blur, and format conversion.
    const fopArr = [{
        fop: 'watermark',
        mode: 2,
        text: 'hello world !',
        dissolve: 50,
        gravity: 'SouthWest',
        fontsize: 500,
        font : '黑体',
        dx: 100,
        dy: 100,
        fill: '#FFF000'
      },{
        fop: 'imageView2',
        mode: 3,
        w: 100,
        h: 100,
        q: 100,
        format: 'png'
      }];
    
    const imgLink = qiniu.pipeline(fopArr, key, domain);
  10. Upload files using qiniu.upload

    master

    The qiniu.upload method returns an observable object. To start the upload, you must call .subscribe() on this object. The subscription returns a subscription object which allows you to cancel the upload using .unsubscribe().

    Parameters:

    • file: The file object to upload.
    • key: The key for the object in Qiniu storage.
    • token: The upload token obtained from your server.
    • putExtra (optional): Additional parameters for the upload.
    • config (optional): Configuration object for the upload process.
  11. Configure upload behavior via InternalConfig

    master

    The InternalConfig object defines the core behavior of the upload process. Key properties include:

    • useCdnDomain: Enable CDN acceleration.
    • checkByServer: Enable server-side verification.
    • checkByMD5: Enable MD5 verification for chunks.
    • forceDirect: Force direct upload.
    • retryCount: Number of times to retry after a failure.
    • uphost: Custom upload domains (array of strings).
    • concurrentRequestLimit: Number of concurrent chunk upload requests.
    • chunkSize: Size of each chunk in MB.
    • upprotocol: Protocol for upload domains ('https' or 'http').
    • region: The upload region.
    • disableStatisticsReport: Disable statistical log reporting.
    • debugLogLevel: Set the logging level (e.g., LogLevel.DEBUG).
  12. Configure upload options and extra metadata

    master

    When performing an upload, you can provide UploadOptions to control the file, the target key, the authentication token, and additional metadata.

    Use putExtra to attach custom information to the file:

    • fname: The original filename.
    • customVars: Custom variables. Keys must start with x:.
    • metadata: Custom metadata. Keys must start with x-qn-meta-.
    • mimeType: The file type setting.