本文从前端方面出发实现浏览器下载大文件的功能。不考虑网络异常、关闭网页等原因造成传输中断的情况。分片下载采用串行方式(并行下载需要对切片计算hash,比对hash,丢失重传,合并chunks的时候需要按顺序合并等,很麻烦。对传输速度有追求的,并且在带宽允许的情况下可以做并行分片下载)。
测试发现存一两个g左右数据到indexeddb后,浏览器确实会内存占用过高导致退出 (我测试使用的是chrome103版本浏览器)
实现步骤
- 使用分片下载: 将大文件分割成多个小块进行下载,可以降低内存占用和网络传输中断的风险。这样可以避免一次性下载整个大文件造成的性能问题。
- 断点续传: 实现断点续传功能,即在下载中途中断后,可以从已下载的部分继续下载,而不需要重新下载整个文件。
- 进度条显示: 在页面上展示下载进度,让用户清晰地看到文件下载的进度。如果一次全部下载可以从process中直接拿到参数计算得出(很精细),如果是分片下载,也是计算已下载的和总大小,只不过已下载的会成片成片的增加(不是很精细)。
- 取消下载和暂停下载功能: 提供取消下载和暂停下载的按钮,让用户可以根据需要中止或暂停下载过程。
- 合并文件: 下载完成后,将所有分片文件合并成一个完整的文件。
以下是一个基本的前端大文件下载的实现示例:
可以在类里面增加注入一个回调函数,用来更新外部的一些状态,示例中只展示下载完成后的回调
class filedownloader {
constructor({url, filename, chunksize = 2 * 1024 * 1024, cb}) {
this.url = url;
this.filename = filename;
this.chunksize = chunksize;
this.filesize = 0;
this.totalchunks = 0;
this.currentchunk = 0;
this.downloadedsize = 0;
this.chunks = [];
this.abortcontroller = new abortcontroller();
this.paused = false;
this.cb = cb
}
async getfilesize() {
const response = await fetch(this.url, { signal: this.abortcontroller.signal });
const contentlength = response.headers.get("content-length");
this.filesize = parseint(contentlength);
this.totalchunks = math.ceil(this.filesize / this.chunksize);
}
async downloadchunk(chunkindex) {
const start = chunkindex * this.chunksize;
const end = math.min(this.filesize, (chunkindex + 1) * this.chunksize - 1);
const response = await fetch(this.url, {
headers: { range: `bytes=${start}-${end}` },
signal: this.abortcontroller.signal
});
const blob = await response.blob();
this.chunks[chunkindex] = blob;
this.downloadedsize += blob.size;
if (!this.paused && this.currentchunk < this.totalchunks - 1) {
this.currentchunk++;
this.downloadchunk(this.currentchunk);
} else if (this.currentchunk === this.totalchunks - 1) {
this.mergechunks();
}
}
async startdownload() {
if (this.chunks.length === 0) {
await this.getfilesize();
}
this.downloadchunk(this.currentchunk);
}
pausedownload() {
this.paused = true;
}
resumedownload() {
this.paused = false;
this.downloadchunk(this.currentchunk);
}
canceldownload() {
this.abortcontroller.abort();
this.reset();
}
async mergechunks() {
const blob = new blob(this.chunks, { type: "application/octet-stream" });
const url = window.url.createobjecturl(blob);
const a = document.createelement("a");
a.href = url;
a.download = this.filename;
document.body.appendchild(a);
a.click();
settimeout(() => {
this.cb && this.cb({
downstate: 1
})
this.reset();
document.body.removechild(a);
window.url.revokeobjecturl(url);
}, 0);
}
reset() {
this.chunks = [];
this.filename = '';
this.filesize = 0;
this.totalchunks = 0;
this.currentchunk = 0;
this.downloadedsize = 0;
}
}
// 使用示例
const url = "https://example.com/largefile.zip";
const filename = "largefile.zip";
const downloader = new filedownloader({url, filename, cb: this.updatedata});
// 更新状态
updatedata(res) {
const {downstate} = res
this.downstate = downstate
}
// 开始下载
downloader.startdownload();
// 暂停下载
// downloader.pausedownload();
// 继续下载
// downloader.resumedownload();
// 取消下载
// downloader.canceldownload();
分片下载怎么实现断点续传?已下载的文件怎么存储?
浏览器的安全策略禁止网页(js)直接访问和操作用户计算机上的文件系统。
在分片下载过程中,每个下载的文件块(chunk)都需要在客户端进行缓存或存储,方便实现断点续传功能,同时也方便后续将这些文件块合并成完整的文件。这些文件块可以暂时保存在内存中或者存储在客户端的本地存储(如 indexeddb、localstorage 等)中。
一般情况下,为了避免占用过多的内存,推荐将文件块暂时保存在客户端的本地存储中。这样可以确保在下载大文件时不会因为内存占用过多而导致性能问题。
在上面提供的示例代码中,文件块是暂时保存在一个数组中的,最终在mergechunks()方法中将这些文件块合并成完整的文件。如果你希望将文件块保存在本地存储中,可以根据需要修改代码,将文件块保存到 indexeddb 或 localstorage 中。
indexeddb本地存储
indexeddb文档:indexeddb_api
无痕模式是浏览器提供的一种隐私保护功能,它会在用户关闭浏览器窗口后自动清除所有的浏览数据,包括 localstorage、indexeddb 和其他存储机制中的数据。
indexeddb 数据实际上存储在浏览器的文件系统中,是浏览器的隐私目录之一,不同浏览器可能会有不同的存储位置,普通用户无法直接访问和手动删除这些文件,因为它们受到浏览器的安全限制。可以使用 deletedatabase 方法来删除整个数据库,或者使用 deleteobjectstore 方法来删除特定的对象存储空间中的数据。
原生的indexeddb api 使用起来很麻烦,稍不留神就会出现各种问题,封装一下方便以后使用。
这个类封装了 indexeddb 的常用操作,包括打开数据库、添加数据、通过 id 获取数据、获取全部数据、更新数据、删除数据和删除数据表。
封装indexeddb类
class indexeddbwrapper {
constructor(dbname, storename) {
this.dbname = dbname;
this.storename = storename;
this.db = null;
}
opendatabase() {
return new promise((resolve, reject) => {
const request = indexeddb.open(this.dbname);
request.onerror = () => {
console.error("failed to open database");
reject();
};
request.onsuccess = () => {
this.db = request.result;
resolve();
};
request.onupgradeneeded = () => {
this.db = request.result;
if (!this.db.objectstorenames.contains(this.storename)) {
this.db.createobjectstore(this.storename, { keypath: "id" });
}
};
});
}
adddata(data) {
return new promise((resolve, reject) => {
const transaction = this.db.transaction([this.storename], "readwrite");
const objectstore = transaction.objectstore(this.storename);
const request = objectstore.add(data);
request.onsuccess = () => {
resolve();
};
request.onerror = () => {
console.error("failed to add data");
reject();
};
});
}
getdatabyid(id) {
return new promise((resolve, reject) => {
const transaction = this.db.transaction([this.storename], "readonly");
const objectstore = transaction.objectstore(this.storename);
const request = objectstore.get(id);
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
console.error(`failed to get data with id: ${id}`);
reject();
};
});
}
getalldata() {
return new promise((resolve, reject) => {
const transaction = this.db.transaction([this.storename], "readonly");
const objectstore = transaction.objectstore(this.storename);
const request = objectstore.getall();
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
console.error("failed to get all data");
reject();
};
});
}
updatedata(data) {
return new promise((resolve, reject) => {
const transaction = this.db.transaction([this.storename], "readwrite");
const objectstore = transaction.objectstore(this.storename);
const request = objectstore.put(data);
request.onsuccess = () => {
resolve();
};
request.onerror = () => {
console.error("failed to update data");
reject();
};
});
}
deletedatabyid(id) {
return new promise((resolve, reject) => {
const transaction = this.db.transaction([this.storename], "readwrite");
const objectstore = transaction.objectstore(this.storename);
const request = objectstore.delete(id);
request.onsuccess = () => {
resolve();
};
request.onerror = () => {
console.error(`failed to delete data with id: ${id}`);
reject();
};
});
}
deletestore() {
return new promise((resolve, reject) => {
const version = this.db.version + 1;
this.db.close();
const request = indexeddb.open(this.dbname, version);
request.onupgradeneeded = () => {
this.db = request.result;
this.db.deleteobjectstore(this.storename);
resolve();
};
request.onsuccess = () => {
resolve();
};
request.onerror = () => {
console.error("failed to delete object store");
reject();
};
});
}
}
使用indexeddb类示例
const dbname = "mydatabase";
const storename = "mystore";
const dbwrapper = new indexeddbwrapper(dbname, storename);
dbwrapper.opendatabase().then(() => {
const data = { id: 1, name: "john doe", age: 30 };
dbwrapper.adddata(data).then(() => {
console.log("data added successfully");
dbwrapper.getdatabyid(1).then((result) => {
console.log("data retrieved:", result);
const updateddata = { id: 1, name: "jane smith", age: 35 };
dbwrapper.updatedata(updateddata).then(() => {
console.log("data updated successfully");
dbwrapper.getdatabyid(1).then((updatedresult) => {
console.log("updated data retrieved:", updatedresult);
dbwrapper.deletedatabyid(1).then(() => {
console.log("data deleted successfully");
dbwrapper.getalldata().then((alldata) => {
console.log("all data:", alldata);
dbwrapper.deletestore().then(() => {
console.log("object store deleted successfully");
});
});
});
});
});
});
});
});
indexeddb的使用库 - localforage
这个库对浏览器本地存储的几种方式做了封装,自动降级处理。但是使用indexeddb上感觉不是很好,不可以添加索引,但是操作确实方便了很多。
文档地址: localforage
下面展示 localforage 中使用 indexeddb 存储引擎并结合 async/await 进行异步操作
const localforage = require('localforage');
// 配置 localforage
localforage.config({
driver: localforage.indexeddb, // 使用 indexeddb 存储引擎
name: 'myapp', // 数据库名称
version: 1.0, // 数据库版本
storename: 'mydata' // 存储表名称
});
// 使用 async/await 进行异步操作
(async () => {
try {
// 存储数据
await localforage.setitem('key', 'value');
console.log('数据保存成功');
// 获取数据
const value = await localforage.getitem('key');
console.log('获取到的数据为:', value);
// 移除数据
await localforage.removeitem('key');
console.log('数据移除成功');
// 关闭 indexeddb 连接
await localforage.close();
console.log('indexeddb 已关闭');
} catch (err) {
console.error('操作失败', err);
}
})();
现代的浏览器会自动管理 indexeddb 连接的生命周期,包括在页面关闭时自动关闭连接,在大多数情况下,不需要显式地打开或关闭 indexeddb 连接。
如果你有特殊的需求或者对性能有更高的要求,可以使用 localforage.close() 方法来关闭连接。
使用 localforage 来删除 indexeddb 中的所有数据
import localforage from 'localforage';
// 使用 clear() 方法删除所有数据
localforage.clear()
.then(() => {
console.log('indexeddb 中的所有数据已删除');
})
.catch((error) => {
console.error('删除 indexeddb 数据时出错:', error);
});
indexeddb内存暂用过高问题
使用 indexeddb 可能会导致浏览器内存占用增加的原因有很多,以下是一些可能的原因:
- 数据量过大:如果你在 indexeddb 中存储了大量数据,那么浏览器可能需要消耗更多内存来管理和处理这些数据。尤其是在读取或写入大量数据时,内存占用会显著增加。
- 未关闭的连接:如果在使用完 indexeddb 后未正确关闭数据库连接,可能会导致内存泄漏。确保在不再需要使用 indexeddb 时正确关闭数据库连接,以释放占用的内存。
- 索引和查询:如果你在 indexeddb 中创建了大量索引或者执行复杂的查询操作,都会导致浏览器内存占用增加,特别是在处理大型数据集时。
- 缓存:浏览器可能会对 indexeddb 中的数据进行缓存,以提高访问速度。这可能会导致内存占用增加,尤其是在大规模数据操作后。
- 浏览器实现:不同浏览器的 indexeddb 实现可能存在差异,某些浏览器可能会在处理 indexeddb 数据时占用更多内存。
为了减少内存占用,你可以考虑优化数据存储结构、合理使用索引、避免长时间保持大型数据集等措施。另外,使用浏览器的开发者工具进行内存分析,可以帮助你找到内存占用增加的具体原因,从而采取相应的优化措施。
以上就是javascript实现下载超大文件的方法详解的详细内容,更多关于javascript下载超大文件的资料请关注代码网其它相关文章!
发表评论