-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathuploader-nginx.ts
62 lines (55 loc) · 1.56 KB
/
uploader-nginx.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { Uploader } from 'ngx-uploadx';
/**
* Implements nginx-upload-module resumable uploads protocol
* {@link https://github.com/fdintino/nginx-upload-module/blob/master/upload-protocol.md nginx-upload-module}
* @example
* options: UploadxOptions = {
* endpoint: '/files'
* uploaderClass: NginxUploadModuleUploader
* };
*/
export class NginxUploadModuleUploader extends Uploader {
offset = 0;
response = '';
async getFileUrl(): Promise<string> {
return this.endpoint;
}
async getOffset(): Promise<number> {
return this.offset;
}
async sendFileContent(): Promise<number> {
const { body, end } = this.getChunk();
const headers = {
'Content-Type': this.file.type,
'Session-ID': `${this.uploadId}`,
'Content-Disposition': `attachment; filename="${encodeURIComponent(this.name)}"`,
'Content-Range': `bytes ${this.offset}-${end - 1}/${this.size}`
};
await this.request({
method: 'POST',
body,
url: this.url,
headers
});
return this.getOffsetFromResponse();
}
// abort not supported
abort(): void {}
private getOffsetFromResponse(): number {
if (this.response && this.responseStatus === 201) {
const [, end] = this.response
.split(/\D+/)
.filter((v: string) => v.length)
.map(Number)
.reverse();
if (isNaN(end)) {
throw new Error('Range is missing!');
}
this.offset = end + 1;
return this.offset;
} else if (this.responseStatus === 200) {
return this.size;
}
return this.offset;
}
}