经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 编程经验 » 查看文章
前端下载超大文件的完整方案
来源:cnblogs  作者:甜点cc  时间:2024/3/27 8:44:29  对本文有异议

本文从前端方面出发实现浏览器下载大文件的功能。不考虑网络异常、关闭网页等原因造成传输中断的情况。分片下载采用串行方式(并行下载需要对切片计算hash,比对hash,丢失重传,合并chunks的时候需要按顺序合并等,很麻烦。对传输速度有追求的,并且在带宽允许的情况下可以做并行分片下载)。

测试发现存一两个G左右数据到IndexedDB后,浏览器确实会内存占用过高导致退出 (我测试使用的是chrome103版本浏览器)

实现步骤

  1. 使用分片下载: 将大文件分割成多个小块进行下载,可以降低内存占用和网络传输中断的风险。这样可以避免一次性下载整个大文件造成的性能问题。

  2. 断点续传: 实现断点续传功能,即在下载中途中断后,可以从已下载的部分继续下载,而不需要重新下载整个文件。

  3. 进度条显示: 在页面上展示下载进度,让用户清晰地看到文件下载的进度。如果一次全部下载可以从process中直接拿到参数计算得出(很精细),如果是分片下载,也是计算已下载的和总大小,只不过已下载的会成片成片的增加(不是很精细)。

  4. 取消下载和暂停下载功能: 提供取消下载和暂停下载的按钮,让用户可以根据需要中止或暂停下载过程。

  5. 合并文件: 下载完成后,将所有分片文件合并成一个完整的文件。

以下是一个基本的前端大文件下载的实现示例:

可以在类里面增加注入一个回调函数,用来更新外部的一些状态,示例中只展示下载完成后的回调

  1. class FileDownloader {
  2. constructor({url, fileName, chunkSize = 2 * 1024 * 1024, cb}) {
  3. this.url = url;
  4. this.fileName = fileName;
  5. this.chunkSize = chunkSize;
  6. this.fileSize = 0;
  7. this.totalChunks = 0;
  8. this.currentChunk = 0;
  9. this.downloadedSize = 0;
  10. this.chunks = [];
  11. this.abortController = new AbortController();
  12. this.paused = false;
  13. this.cb = cb
  14. }
  15. async getFileSize() {
  16. const response = await fetch(this.url, { signal: this.abortController.signal });
  17. const contentLength = response.headers.get("content-length");
  18. this.fileSize = parseInt(contentLength);
  19. this.totalChunks = Math.ceil(this.fileSize / this.chunkSize);
  20. }
  21. async downloadChunk(chunkIndex) {
  22. const start = chunkIndex * this.chunkSize;
  23. const end = Math.min(this.fileSize, (chunkIndex + 1) * this.chunkSize - 1);
  24. const response = await fetch(this.url, {
  25. headers: { Range: `bytes=${start}-${end}` },
  26. signal: this.abortController.signal
  27. });
  28. const blob = await response.blob();
  29. this.chunks[chunkIndex] = blob;
  30. this.downloadedSize += blob.size;
  31. if (!this.paused && this.currentChunk < this.totalChunks - 1) {
  32. this.currentChunk++;
  33. this.downloadChunk(this.currentChunk);
  34. } else if (this.currentChunk === this.totalChunks - 1) {
  35. this.mergeChunks();
  36. }
  37. }
  38. async startDownload() {
  39. if (this.chunks.length === 0) {
  40. await this.getFileSize();
  41. }
  42. this.downloadChunk(this.currentChunk);
  43. }
  44. pauseDownload() {
  45. this.paused = true;
  46. }
  47. resumeDownload() {
  48. this.paused = false;
  49. this.downloadChunk(this.currentChunk);
  50. }
  51. cancelDownload() {
  52. this.abortController.abort();
  53. this.reset();
  54. }
  55. async mergeChunks() {
  56. const blob = new Blob(this.chunks, { type: "application/octet-stream" });
  57. const url = window.URL.createObjectURL(blob);
  58. const a = document.createElement("a");
  59. a.href = url;
  60. a.download = this.fileName;
  61. document.body.appendChild(a);
  62. a.click();
  63. setTimeout(() => {
  64. this.cb && this.cb({
  65. downState: 1
  66. })
  67. this.reset();
  68. document.body.removeChild(a);
  69. window.URL.revokeObjectURL(url);
  70. }, 0);
  71. }
  72. reset() {
  73. this.chunks = [];
  74. this.fileName = '';
  75. this.fileSize = 0;
  76. this.totalChunks = 0;
  77. this.currentChunk = 0;
  78. this.downloadedSize = 0;
  79. }
  80. }
  81. // 使用示例
  82. const url = "https://example.com/largefile.zip";
  83. const fileName = "largefile.zip";
  84. const downloader = new FileDownloader({url, fileName, cb: this.updateData});
  85. // 更新状态
  86. updateData(res) {
  87. const {downState} = res
  88. this.downState = downState
  89. }
  90. // 开始下载
  91. downloader.startDownload();
  92. // 暂停下载
  93. // downloader.pauseDownload();
  94. // 继续下载
  95. // downloader.resumeDownload();
  96. // 取消下载
  97. // downloader.cancelDownload();

分片下载怎么实现断点续传?已下载的文件怎么存储?

浏览器的安全策略禁止网页(JS)直接访问和操作用户计算机上的文件系统。

在分片下载过程中,每个下载的文件块(chunk)都需要在客户端进行缓存或存储,方便实现断点续传功能,同时也方便后续将这些文件块合并成完整的文件。这些文件块可以暂时保存在内存中或者存储在客户端的本地存储(如 IndexedDB、LocalStorage 等)中。

一般情况下,为了避免占用过多的内存,推荐将文件块暂时保存在客户端的本地存储中。这样可以确保在下载大文件时不会因为内存占用过多而导致性能问题。

在上面提供的示例代码中,文件块是暂时保存在一个数组中的,最终在mergeChunks()方法中将这些文件块合并成完整的文件。如果你希望将文件块保存在本地存储中,可以根据需要修改代码,将文件块保存到 IndexedDB 或 LocalStorage 中。

IndexedDB本地存储

IndexedDB文档:IndexedDB_API

IndexedDB 浏览器存储限制和清理标准

无痕模式是浏览器提供的一种隐私保护功能,它会在用户关闭浏览器窗口后自动清除所有的浏览数据,包括 LocalStorage、IndexedDB 和其他存储机制中的数据。

IndexedDB 数据实际上存储在浏览器的文件系统中,是浏览器的隐私目录之一,不同浏览器可能会有不同的存储位置,普通用户无法直接访问和手动删除这些文件,因为它们受到浏览器的安全限制。可以使用 deleteDatabase 方法来删除整个数据库,或者使用 deleteObjectStore 方法来删除特定的对象存储空间中的数据。

原生的indexedDB api 使用起来很麻烦,稍不留神就会出现各种问题,封装一下方便以后使用。

这个类封装了 IndexedDB 的常用操作,包括打开数据库、添加数据、通过 ID 获取数据、获取全部数据、更新数据、删除数据和删除数据表。

封装indexedDB类

  1. class IndexedDBWrapper {
  2. constructor(dbName, storeName) {
  3. this.dbName = dbName;
  4. this.storeName = storeName;
  5. this.db = null;
  6. }
  7. openDatabase() {
  8. return new Promise((resolve, reject) => {
  9. const request = indexedDB.open(this.dbName);
  10. request.onerror = () => {
  11. console.error("Failed to open database");
  12. reject();
  13. };
  14. request.onsuccess = () => {
  15. this.db = request.result;
  16. resolve();
  17. };
  18. request.onupgradeneeded = () => {
  19. this.db = request.result;
  20. if (!this.db.objectStoreNames.contains(this.storeName)) {
  21. this.db.createObjectStore(this.storeName, { keyPath: "id" });
  22. }
  23. };
  24. });
  25. }
  26. addData(data) {
  27. return new Promise((resolve, reject) => {
  28. const transaction = this.db.transaction([this.storeName], "readwrite");
  29. const objectStore = transaction.objectStore(this.storeName);
  30. const request = objectStore.add(data);
  31. request.onsuccess = () => {
  32. resolve();
  33. };
  34. request.onerror = () => {
  35. console.error("Failed to add data");
  36. reject();
  37. };
  38. });
  39. }
  40. getDataById(id) {
  41. return new Promise((resolve, reject) => {
  42. const transaction = this.db.transaction([this.storeName], "readonly");
  43. const objectStore = transaction.objectStore(this.storeName);
  44. const request = objectStore.get(id);
  45. request.onsuccess = () => {
  46. resolve(request.result);
  47. };
  48. request.onerror = () => {
  49. console.error(`Failed to get data with id: ${id}`);
  50. reject();
  51. };
  52. });
  53. }
  54. getAllData() {
  55. return new Promise((resolve, reject) => {
  56. const transaction = this.db.transaction([this.storeName], "readonly");
  57. const objectStore = transaction.objectStore(this.storeName);
  58. const request = objectStore.getAll();
  59. request.onsuccess = () => {
  60. resolve(request.result);
  61. };
  62. request.onerror = () => {
  63. console.error("Failed to get all data");
  64. reject();
  65. };
  66. });
  67. }
  68. updateData(data) {
  69. return new Promise((resolve, reject) => {
  70. const transaction = this.db.transaction([this.storeName], "readwrite");
  71. const objectStore = transaction.objectStore(this.storeName);
  72. const request = objectStore.put(data);
  73. request.onsuccess = () => {
  74. resolve();
  75. };
  76. request.onerror = () => {
  77. console.error("Failed to update data");
  78. reject();
  79. };
  80. });
  81. }
  82. deleteDataById(id) {
  83. return new Promise((resolve, reject) => {
  84. const transaction = this.db.transaction([this.storeName], "readwrite");
  85. const objectStore = transaction.objectStore(this.storeName);
  86. const request = objectStore.delete(id);
  87. request.onsuccess = () => {
  88. resolve();
  89. };
  90. request.onerror = () => {
  91. console.error(`Failed to delete data with id: ${id}`);
  92. reject();
  93. };
  94. });
  95. }
  96. deleteStore() {
  97. return new Promise((resolve, reject) => {
  98. const version = this.db.version + 1;
  99. this.db.close();
  100. const request = indexedDB.open(this.dbName, version);
  101. request.onupgradeneeded = () => {
  102. this.db = request.result;
  103. this.db.deleteObjectStore(this.storeName);
  104. resolve();
  105. };
  106. request.onsuccess = () => {
  107. resolve();
  108. };
  109. request.onerror = () => {
  110. console.error("Failed to delete object store");
  111. reject();
  112. };
  113. });
  114. }
  115. }

使用indexedDB类示例:

  1. const dbName = "myDatabase";
  2. const storeName = "myStore";
  3. const dbWrapper = new IndexedDBWrapper(dbName, storeName);
  4. dbWrapper.openDatabase().then(() => {
  5. const data = { id: 1, name: "John Doe", age: 30 };
  6. dbWrapper.addData(data).then(() => {
  7. console.log("Data added successfully");
  8. dbWrapper.getDataById(1).then((result) => {
  9. console.log("Data retrieved:", result);
  10. const updatedData = { id: 1, name: "Jane Smith", age: 35 };
  11. dbWrapper.updateData(updatedData).then(() => {
  12. console.log("Data updated successfully");
  13. dbWrapper.getDataById(1).then((updatedResult) => {
  14. console.log("Updated data retrieved:", updatedResult);
  15. dbWrapper.deleteDataById(1).then(() => {
  16. console.log("Data deleted successfully");
  17. dbWrapper.getAllData().then((allData) => {
  18. console.log("All data:", allData);
  19. dbWrapper.deleteStore().then(() => {
  20. console.log("Object store deleted successfully");
  21. });
  22. });
  23. });
  24. });
  25. });
  26. });
  27. });
  28. });

indexedDB的使用库 - localforage

这个库对浏览器本地存储的几种方式做了封装,自动降级处理。但是使用indexedDB上感觉不是很好,不可以添加索引,但是操作确实方便了很多。

文档地址: localforage

下面展示 LocalForage 中使用 IndexedDB 存储引擎并结合 async/await 进行异步操作

  1. const localforage = require('localforage');
  2. // 配置 LocalForage
  3. localforage.config({
  4. driver: localforage.INDEXEDDB, // 使用 IndexedDB 存储引擎
  5. name: 'myApp', // 数据库名称
  6. version: 1.0, // 数据库版本
  7. storeName: 'myData' // 存储表名称
  8. });
  9. // 使用 async/await 进行异步操作
  10. (async () => {
  11. try {
  12. // 存储数据
  13. await localforage.setItem('key', 'value');
  14. console.log('数据保存成功');
  15. // 获取数据
  16. const value = await localforage.getItem('key');
  17. console.log('获取到的数据为:', value);
  18. // 移除数据
  19. await localforage.removeItem('key');
  20. console.log('数据移除成功');
  21. // 关闭 IndexedDB 连接
  22. await localforage.close();
  23. console.log('IndexedDB 已关闭');
  24. } catch (err) {
  25. console.error('操作失败', err);
  26. }
  27. })();

现代的浏览器会自动管理 IndexedDB 连接的生命周期,包括在页面关闭时自动关闭连接,在大多数情况下,不需要显式地打开或关闭 IndexedDB 连接。

如果你有特殊的需求或者对性能有更高的要求,可以使用 localforage.close() 方法来关闭连接。

使用 LocalForage 来删除 IndexedDB 中的所有数据

  1. import localforage from 'localforage';
  2. // 使用 clear() 方法删除所有数据
  3. localforage.clear()
  4. .then(() => {
  5. console.log('IndexedDB 中的所有数据已删除');
  6. })
  7. .catch((error) => {
  8. console.error('删除 IndexedDB 数据时出错:', error);
  9. });

IndexedDB内存暂用过高问题

使用 IndexedDB 可能会导致浏览器内存占用增加的原因有很多,以下是一些可能的原因:

  1. 数据量过大:如果你在 IndexedDB 中存储了大量数据,那么浏览器可能需要消耗更多内存来管理和处理这些数据。尤其是在读取或写入大量数据时,内存占用会显著增加。

  2. 未关闭的连接:如果在使用完 IndexedDB 后未正确关闭数据库连接,可能会导致内存泄漏。确保在不再需要使用 IndexedDB 时正确关闭数据库连接,以释放占用的内存。

  3. 索引和查询:如果你在 IndexedDB 中创建了大量索引或者执行复杂的查询操作,都会导致浏览器内存占用增加,特别是在处理大型数据集时。

  4. 缓存:浏览器可能会对 IndexedDB 中的数据进行缓存,以提高访问速度。这可能会导致内存占用增加,尤其是在大规模数据操作后。

  5. 浏览器实现:不同浏览器的 IndexedDB 实现可能存在差异,某些浏览器可能会在处理 IndexedDB 数据时占用更多内存。

为了减少内存占用,你可以考虑优化数据存储结构、合理使用索引、避免长时间保持大型数据集等措施。另外,使用浏览器的开发者工具进行内存分析,可以帮助你找到内存占用增加的具体原因,从而采取相应的优化措施。


我是 甜点cc,个人网站: blog.i-xiao.space/

唯有行动,才能战胜虚无!

公众号:【看见另一种可能】

原文链接:https://www.cnblogs.com/all-smile/p/18096224

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号