Last active
September 19, 2021 12:41
-
-
Save gpDA/a3c3e1b632484a0ba1cf69e8dfd71709 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// want to go over | |
// 1 - use fo constants | |
// 2 - cancelToken | |
// 3 - progress upload + how `numberOfRequests` is being used to represent the multiple requests | |
// 4 - `uploadFileResponseHelper` & `uploadFileErrorHelper` helper functions | |
// constants/file.constants.js | |
const CHUNK_SIZE = 1000 * 1000 * 100; // 100mb | |
export { | |
CHUNK_SIZE, | |
} | |
// store/modules/carfsModule.ts | |
async function uploadFile(filefromParams: File, | |
totalBytesUploaded?: number, | |
prevTotalFromParams?: number, | |
index?: number, | |
permissionList?: Array<FSPermissions>): Promise<void> { | |
const file = filefromParams; | |
const source = axios.CancelToken.source(); | |
// chunked upload | |
if (file.slice().size > CHUNK_SIZE) { // if > 100mb (greater than 100mb) | |
const progress = { | |
title: file.name, | |
loaded: totalBytesUploaded || 0, | |
total: file.slice().size, | |
success: false, | |
failure: false, | |
failureCause: '', | |
cancel: () => { source.cancel(); }, | |
} as FileProgress; | |
carfsModule.setFileUploadProgress([...carfsModule.fileUploadProgress, progress]); | |
try { | |
await checkDirectoryName(); | |
let numberOfRequests = totalBytesUploaded ? Math.floor(totalBytesUploaded / CHUNK_SIZE) : 0; | |
// request | |
const chunkUploadResponse = await carfsApi.chunkUpload(carfsModule.directory, file, | |
totalBytesUploaded, permissionList, | |
(e) => { | |
progress.loaded = e.loaded + e.total * numberOfRequests | |
prevTotal = e.total | |
if(e.loaded === e.total) { | |
numberOfRequests += 1; | |
} | |
}, source.token) | |
// helper function | |
uploadFileResponseHelper(chunkUploadResponse, progress); | |
} catch (error) { | |
// helper function | |
uploadFileErrorHelper(error, progress, file); | |
} | |
} | |
function uploadFileResponseHelper(uploadParams: FSReport, progress: Progress): void { | |
progress.success = true; | |
carfsModule.setFilePaths( | |
[...carfsModule.filePaths, { | |
path: uploadParams.filePath || '', | |
sizeBytes: uploadParams.fileSize || 0, | |
}], | |
); | |
} | |
function uploadFileErrorHelper(error: any, progress: Progress, file: File) { | |
if (axios.isCancel(error)) { | |
progress.failure = true; | |
progress.failureCause = 'UserCancel'; | |
} else { | |
progress.failure = true; | |
progress.failureCause = error || 'unknown error'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment