JavaScript SDK for Qiniu Cloud Storage that enables browser-based file uploads with resumable transfer, image processing, and comprehensive error handling.
npx @tessl/cli install tessl/npm-qiniu-js@3.4.0Qiniu JavaScript SDK is a comprehensive client-side library for Qiniu Cloud Storage that enables browser-based file uploads with resumable transfer capabilities, advanced image processing, and comprehensive error handling. It supports both direct upload for small files and chunked upload with resume functionality for larger files.
npm install qiniu-jsimport { upload, region } from "qiniu-js";For specific functionality:
import {
upload,
imageMogr2,
watermark,
imageInfo,
exif,
pipeline,
compressImage,
QiniuError,
QiniuRequestError,
QiniuNetworkError
} from "qiniu-js";For CommonJS:
const { upload, region, imageMogr2, watermark } = require("qiniu-js");import { upload, region } from "qiniu-js";
// Basic file upload
const file = document.getElementById('fileInput').files[0];
const key = 'my-file.jpg'; // Target filename, can be null for auto-generated
const token = 'your-upload-token'; // Get from your server
const observable = upload(file, key, token, {
fname: file.name,
customVars: {
'x:user': 'alice'
}
}, {
region: region.z0,
useCdnDomain: true,
retryCount: 3
});
// Subscribe to upload progress
const subscription = observable.subscribe({
next: (progress) => {
console.log(`Progress: ${progress.total.percent}%`);
},
error: (error) => {
console.error('Upload failed:', error);
},
complete: (response) => {
console.log('Upload successful:', response);
}
});
// Cancel upload if needed
// subscription.unsubscribe();Qiniu JavaScript SDK is built around several key components:
Core file upload functionality with automatic upload strategy selection, progress tracking, and resume capabilities for large files.
function upload(
file: File,
key: string | null | undefined,
token: string,
putExtra?: Partial<Extra>,
config?: Config
): Observable<UploadProgress, QiniuError | QiniuRequestError | QiniuNetworkError, UploadCompleteData>;
interface Extra {
fname: string;
customVars?: { [key: string]: string };
metadata?: { [key: string]: string };
mimeType?: string;
}
interface Config {
useCdnDomain?: boolean;
region?: string;
forceDirect?: boolean;
retryCount?: number;
chunkSize?: number;
concurrentRequestLimit?: number;
upprotocol?: 'https' | 'http';
disableStatisticsReport?: boolean;
}Comprehensive image processing capabilities including thumbnails, advanced transformations, watermarks, and metadata extraction.
function imageMogr2(op: ImageMogr2, key?: string, domain?: string): string;
function watermark(op: ImageWatermark, key?: string, domain?: string): string;
function imageInfo(key: string, domain: string): Promise<ResponseSuccess<any>>;
function exif(key: string, domain: string): Promise<ResponseSuccess<any>>;
function pipeline(arr: Pipeline[], key?: string, domain?: string): string;
interface ImageMogr2 {
'auto-orient'?: boolean;
strip?: boolean;
thumbnail?: number;
crop?: number;
gravity?: number;
format?: number;
blur?: number;
quality?: number;
rotate?: number;
}
interface ImageWatermark {
image?: string;
mode: number;
fontsize?: number;
dissolve?: number;
dx?: number;
dy?: number;
gravity?: string;
text?: string;
font?: string;
fill?: string;
}Comprehensive error handling system with specific error types for different failure scenarios and automatic retry mechanisms.
enum QiniuErrorName {
InvalidFile = 'InvalidFile',
InvalidToken = 'InvalidToken',
InvalidMetadata = 'InvalidMetadata',
InvalidChunkSize = 'InvalidChunkSize',
InvalidCustomVars = 'InvalidCustomVars',
NotAvailableUploadHost = 'NotAvailableUploadHost',
ReadCacheFailed = 'ReadCacheFailed',
InvalidCacheData = 'InvalidCacheData',
WriteCacheFailed = 'WriteCacheFailed',
RemoveCacheFailed = 'RemoveCacheFailed',
GetCanvasContextFailed = 'GetCanvasContextFailed',
UnsupportedFileType = 'UnsupportedFileType',
FileReaderReadFailed = 'FileReaderReadFailed',
NotAvailableXMLHttpRequest = 'NotAvailableXMLHttpRequest',
InvalidProgressEventTarget = 'InvalidProgressEventTarget',
RequestError = 'RequestError'
}
class QiniuError implements Error {
constructor(public name: QiniuErrorName, public message: string);
}
class QiniuRequestError extends QiniuError {
constructor(public code: number, public reqId: string, message: string, data?: any);
}
class QiniuNetworkError extends QiniuRequestError {
constructor(message: string, reqId?: string);
}Helper functions for image compression, base64 encoding, and upload configuration management.
function compressImage(file: File, options: CompressOptions): Promise<CompressResult>;
function urlSafeBase64Encode(v: any): string;
function urlSafeBase64Decode(v: any): string;
function getHeadersForMkFile(token: string): { [key: string]: string };
function getHeadersForChunkUpload(token: string): { [key: string]: string };
interface CompressOptions {
quality?: number;
noCompressIfLarger?: boolean;
maxWidth?: number;
maxHeight?: number;
}
interface CompressResult {
dist: Blob | File;
width: number;
height: number;
}Regional configuration and upload settings for optimal performance across different geographic locations.
const region = {
z0: 'z0',
z1: 'z1',
z2: 'z2',
na0: 'na0',
as0: 'as0',
cnEast2: 'cn-east-2'
} as const;
function deleteUploadedChunks(
token: string,
key: string | null | undefined,
uploadinfo: UploadInfo
): Promise<ResponseSuccess<void>>;
function getUploadUrl(config: UploadUrlConfig, token: string): Promise<string>;interface Observable<T, E, R> {
subscribe(observer: {
next?: (value: T) => void;
error?: (error: E) => void;
complete?: (result: R) => void;
}): { unsubscribe(): void };
}
interface UploadProgress {
total: ProgressCompose;
uploadInfo?: UploadInfo;
chunks?: ProgressCompose[];
}
interface ProgressCompose {
size: number;
loaded: number;
percent: number;
fromCache?: boolean;
}
interface UploadInfo {
id: string;
url: string;
}
interface ResponseSuccess<T> {
data: T;
reqId: string;
}
type UploadCompleteData = any;