Estoy tratando de descargar varios archivos usando la biblioteca react-native-fs y mostrar el progreso de la descarga al usuario. Para descargar un solo archivo, se puede usar como el siguiente código.
let fileSize = null; let downloadedSize = null; let progress = null; RNFS.downloadFile({ fromUrl: 'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4', toFile: `${RNFS.DocumentDirectoryPath}/download.mp4`, begin: ({jobId, contentLength}) => { fileSize = contentLength; }, progress: ({jobId, bytesWritten, contentLength}) => { downloadedSize = bytesWritten; console.log("progress", downloadedSize / fileSize); }, });
Para descargas de archivos múltiples, estoy tratando de usar la misma función con un bucle for of . Pero no fue capaz de obtener el progreso correctamente. Los valores de progreso se muestran así
0,10,20,30,40,50,60,70,80,90,50,60,70,80,90,80,90,100
Los valores van y vienen. El siguiente es mi código
const files = [ 'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4', 'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_640_3MG.mp4', 'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_1280_10MG.mp4', 'https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_1920_18MG.mp4', ]; const promises = []; let jobs = []; let index = 1; for (const file of files) { const promise = RNFS.downloadFile({ fromUrl: file, toFile: `${RNFS.DocumentDirectoryPath}/download_${index}.mp4`, begin: ({ jobId, contentLength }) => { jobs.push({ jobId, contentLength, progress: 0 }) }, progress: ({ jobId, bytesWritten, contentLength }) => { jobs = jobs.map((job, index) => { if (jobId === job.jobId) { jobs[index].progress = bytesWritten; } return job; }); const totalDownloadSize = jobs.reduce((total, current) => total + current.contentLength, 0); const currentDownloadSize = jobs.reduce((total, current) => total + current.progress, 0); console.log("progress", currentDownloadSize / totalDownloadSize); }, }); promises.push(promise); index++; } Promise.all(promises);
¿Hay alguna manera de que pueda obtener el progreso correctamente?
yo mediría
(currentDownloadSize / totalDownloadSize) * (jobs.length / files.length)
para tener en cuenta los trabajos que aún no han comenzado.