Skip to content
This repository was archived by the owner on Apr 6, 2022. It is now read-only.

Added fetch with progress #25

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ dist/
.rts2_cache_umd/
.env
npm-debug.log
.idea/
5 changes: 3 additions & 2 deletions src/S3Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { throwError } from "./ErrorThrower";
import GetUrl from "./Url";
import Policy from "./Policy";
import Signature from "./Signature";
import {fetchWithProgress} from "./utils";

class S3Client {
private config: IConfig;
constructor(config: IConfig) {
this.config = config;
}
public async uploadFile(file: File, newFileName?: string): Promise<UploadResponse> {
public async uploadFile(file: File, newFileName: string, progressCb: ((this: XMLHttpRequest, ev: ProgressEvent) => any) ): Promise<UploadResponse> {
throwError(this.config, file);

const fd = new FormData();
Expand All @@ -38,7 +39,7 @@ class S3Client {
);
fd.append("file", file);

const data = await fetch(url, { method: "post", body: fd });
const data = await fetchWithProgress(url, { method: "post", body: fd }, progressCb);
if (!data.ok) return Promise.reject(data);
return Promise.resolve({
bucket: this.config.bucketName,
Expand Down
57 changes: 57 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

interface ProgressResponse{
ok: boolean,
status: number,
event: XMLHttpRequest,
}

/**
* Fetch with porgress callback
* @param url
* @param opts
* @param onProgress
* @returns {Promise}
*/
export function fetchWithProgress (url: string, opts: RequestInit, onProgress?: ((this: XMLHttpRequest, ev: ProgressEvent) => any)): Promise<Response | ProgressResponse> {

if(onProgress){ // Backward compatibility

return new Promise( (res, rej)=>{
let xhr = new XMLHttpRequest();
xhr.open(opts.method || 'get', url, true);
xhr.onreadystatechange = function(){
if( this.readyState === 4) {
if( 200 <= this.status && 299 >= this.status ){
let response ={
ok: true,
status: this.status,
event: this
};
res(response)
}else{
rej({
ok:false,
status: this.status,
event: this
})
}
}
};
for (let k in opts.headers || {}) {
//@ts-ignore
xhr.setRequestHeader(k, opts.headers[k]);
}
xhr.onload = function(){
res(this.response);
};
xhr.onerror = e => rej;
if (xhr.upload && onProgress)
xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
xhr.send(opts.body);
});
}else{
return fetch(url, opts)
}

}