or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-qiniu-js

JavaScript SDK for Qiniu Cloud Storage that enables browser-based file uploads with resumable transfer, image processing, and comprehensive error handling.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/qiniu-js@3.4.x

To install, run

npx @tessl/cli install tessl/npm-qiniu-js@3.4.0

0

# Qiniu JavaScript SDK

1

2

Qiniu 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.

3

4

## Package Information

5

6

- **Package Name**: qiniu-js

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install qiniu-js`

10

- **Browser Support**: IE11+, Chrome, Firefox, Safari, Edge

11

12

## Core Imports

13

14

```typescript

15

import { upload, region } from "qiniu-js";

16

```

17

18

For specific functionality:

19

20

```typescript

21

import {

22

upload,

23

imageMogr2,

24

watermark,

25

imageInfo,

26

exif,

27

pipeline,

28

compressImage,

29

QiniuError,

30

QiniuRequestError,

31

QiniuNetworkError

32

} from "qiniu-js";

33

```

34

35

For CommonJS:

36

37

```javascript

38

const { upload, region, imageMogr2, watermark } = require("qiniu-js");

39

```

40

41

## Basic Usage

42

43

```typescript

44

import { upload, region } from "qiniu-js";

45

46

// Basic file upload

47

const file = document.getElementById('fileInput').files[0];

48

const key = 'my-file.jpg'; // Target filename, can be null for auto-generated

49

const token = 'your-upload-token'; // Get from your server

50

51

const observable = upload(file, key, token, {

52

fname: file.name,

53

customVars: {

54

'x:user': 'alice'

55

}

56

}, {

57

region: region.z0,

58

useCdnDomain: true,

59

retryCount: 3

60

});

61

62

// Subscribe to upload progress

63

const subscription = observable.subscribe({

64

next: (progress) => {

65

console.log(`Progress: ${progress.total.percent}%`);

66

},

67

error: (error) => {

68

console.error('Upload failed:', error);

69

},

70

complete: (response) => {

71

console.log('Upload successful:', response);

72

}

73

});

74

75

// Cancel upload if needed

76

// subscription.unsubscribe();

77

```

78

79

## Architecture

80

81

Qiniu JavaScript SDK is built around several key components:

82

83

- **Upload System**: Smart upload manager that automatically chooses between direct upload (files ≤4MB) and resumable chunked upload (files >4MB)

84

- **Observable Pattern**: RxJS-style observable interface for upload lifecycle management with progress tracking

85

- **Error Handling**: Comprehensive error classification with retry mechanisms and host switching

86

- **Image Processing**: Complete suite of image manipulation functions for thumbnails, watermarks, and advanced processing

87

- **Region Management**: Multi-region support with automatic host selection and failover

88

- **Browser Compatibility**: Broad browser support with polyfills for older environments

89

90

## Capabilities

91

92

### File Upload

93

94

Core file upload functionality with automatic upload strategy selection, progress tracking, and resume capabilities for large files.

95

96

```typescript { .api }

97

function upload(

98

file: File,

99

key: string | null | undefined,

100

token: string,

101

putExtra?: Partial<Extra>,

102

config?: Config

103

): Observable<UploadProgress, QiniuError | QiniuRequestError | QiniuNetworkError, UploadCompleteData>;

104

105

interface Extra {

106

fname: string;

107

customVars?: { [key: string]: string };

108

metadata?: { [key: string]: string };

109

mimeType?: string;

110

}

111

112

interface Config {

113

useCdnDomain?: boolean;

114

region?: string;

115

forceDirect?: boolean;

116

retryCount?: number;

117

chunkSize?: number;

118

concurrentRequestLimit?: number;

119

upprotocol?: 'https' | 'http';

120

disableStatisticsReport?: boolean;

121

}

122

```

123

124

[File Upload](./upload.md)

125

126

### Image Processing

127

128

Comprehensive image processing capabilities including thumbnails, advanced transformations, watermarks, and metadata extraction.

129

130

```typescript { .api }

131

function imageMogr2(op: ImageMogr2, key?: string, domain?: string): string;

132

function watermark(op: ImageWatermark, key?: string, domain?: string): string;

133

function imageInfo(key: string, domain: string): Promise<ResponseSuccess<any>>;

134

function exif(key: string, domain: string): Promise<ResponseSuccess<any>>;

135

function pipeline(arr: Pipeline[], key?: string, domain?: string): string;

136

137

interface ImageMogr2 {

138

'auto-orient'?: boolean;

139

strip?: boolean;

140

thumbnail?: number;

141

crop?: number;

142

gravity?: number;

143

format?: number;

144

blur?: number;

145

quality?: number;

146

rotate?: number;

147

}

148

149

interface ImageWatermark {

150

image?: string;

151

mode: number;

152

fontsize?: number;

153

dissolve?: number;

154

dx?: number;

155

dy?: number;

156

gravity?: string;

157

text?: string;

158

font?: string;

159

fill?: string;

160

}

161

```

162

163

[Image Processing](./image-processing.md)

164

165

### Error Handling

166

167

Comprehensive error handling system with specific error types for different failure scenarios and automatic retry mechanisms.

168

169

```typescript { .api }

170

enum QiniuErrorName {

171

InvalidFile = 'InvalidFile',

172

InvalidToken = 'InvalidToken',

173

InvalidMetadata = 'InvalidMetadata',

174

InvalidChunkSize = 'InvalidChunkSize',

175

InvalidCustomVars = 'InvalidCustomVars',

176

NotAvailableUploadHost = 'NotAvailableUploadHost',

177

ReadCacheFailed = 'ReadCacheFailed',

178

InvalidCacheData = 'InvalidCacheData',

179

WriteCacheFailed = 'WriteCacheFailed',

180

RemoveCacheFailed = 'RemoveCacheFailed',

181

GetCanvasContextFailed = 'GetCanvasContextFailed',

182

UnsupportedFileType = 'UnsupportedFileType',

183

FileReaderReadFailed = 'FileReaderReadFailed',

184

NotAvailableXMLHttpRequest = 'NotAvailableXMLHttpRequest',

185

InvalidProgressEventTarget = 'InvalidProgressEventTarget',

186

RequestError = 'RequestError'

187

}

188

189

class QiniuError implements Error {

190

constructor(public name: QiniuErrorName, public message: string);

191

}

192

193

class QiniuRequestError extends QiniuError {

194

constructor(public code: number, public reqId: string, message: string, data?: any);

195

}

196

197

class QiniuNetworkError extends QiniuRequestError {

198

constructor(message: string, reqId?: string);

199

}

200

```

201

202

[Error Handling](./error-handling.md)

203

204

### Utility Functions

205

206

Helper functions for image compression, base64 encoding, and upload configuration management.

207

208

```typescript { .api }

209

function compressImage(file: File, options: CompressOptions): Promise<CompressResult>;

210

function urlSafeBase64Encode(v: any): string;

211

function urlSafeBase64Decode(v: any): string;

212

function getHeadersForMkFile(token: string): { [key: string]: string };

213

function getHeadersForChunkUpload(token: string): { [key: string]: string };

214

215

interface CompressOptions {

216

quality?: number;

217

noCompressIfLarger?: boolean;

218

maxWidth?: number;

219

maxHeight?: number;

220

}

221

222

interface CompressResult {

223

dist: Blob | File;

224

width: number;

225

height: number;

226

}

227

```

228

229

[Utilities](./utilities.md)

230

231

### Configuration & Regions

232

233

Regional configuration and upload settings for optimal performance across different geographic locations.

234

235

```typescript { .api }

236

const region = {

237

z0: 'z0',

238

z1: 'z1',

239

z2: 'z2',

240

na0: 'na0',

241

as0: 'as0',

242

cnEast2: 'cn-east-2'

243

} as const;

244

245

function deleteUploadedChunks(

246

token: string,

247

key: string | null | undefined,

248

uploadinfo: UploadInfo

249

): Promise<ResponseSuccess<void>>;

250

251

function getUploadUrl(config: UploadUrlConfig, token: string): Promise<string>;

252

```

253

254

[Configuration](./configuration.md)

255

256

## Common Types

257

258

```typescript { .api }

259

interface Observable<T, E, R> {

260

subscribe(observer: {

261

next?: (value: T) => void;

262

error?: (error: E) => void;

263

complete?: (result: R) => void;

264

}): { unsubscribe(): void };

265

}

266

267

interface UploadProgress {

268

total: ProgressCompose;

269

uploadInfo?: UploadInfo;

270

chunks?: ProgressCompose[];

271

}

272

273

interface ProgressCompose {

274

size: number;

275

loaded: number;

276

percent: number;

277

fromCache?: boolean;

278

}

279

280

interface UploadInfo {

281

id: string;

282

url: string;

283

}

284

285

interface ResponseSuccess<T> {

286

data: T;

287

reqId: string;

288

}

289

290

type UploadCompleteData = any;

291

```