如何在JSZip中重命名或移动文件/文件夹?
JSZip 文件/文件夹重命名/移动实现方案
JSZip 本身没有内置的 rename 方法,但可以通过复制原内容到新路径 + 删除原条目的方式实现,代码量很小,完全适配浏览器环境。
1. 文件重命名/移动
直接获取原文件的内容,用新文件名重新添加到Zip包,再删除原文件即可:
const zip = new JSZip(); // 先添加测试文件 zip.file("file.txt", "File Content"); // 重命名操作 const oldPath = "file.txt"; const newPath = "newname.txt"; // 异步获取原文件内容(通用适配所有文件类型) zip.file(oldPath).async("arraybuffer").then(content => { // 添加新路径的文件 zip.file(newPath, content); // 删除原文件 zip.remove(oldPath); });
如果是刚添加的文件,也可以直接复用已有的内容变量,省去异步步骤:
const zip = new JSZip(); const fileContent = "File Content"; zip.file("file.txt", fileContent); // 直接用已有内容创建新文件 zip.file("newname.txt", fileContent); zip.remove("file.txt");
2. 文件夹重命名/移动
文件夹需要遍历内部所有条目,逐个复制到新路径下,最后删除原文件夹:
const zip = new JSZip(); // 创建测试文件夹及子文件 zip.folder("oldFolder").file("subfile.txt", "Sub Content"); // 文件夹重命名操作 const oldFolderPath = "oldFolder"; const newFolderPath = "newFolder"; // 获取原文件夹对象 const oldFolder = zip.folder(oldFolderPath); // 遍历文件夹下所有条目 oldFolder.forEach((relativePath, file) => { // 构建新路径:新文件夹名 + 原相对路径 const newPath = `${newFolderPath}/${relativePath}`; // 复制条目到新路径 zip.file(newPath, file); }); // 删除原文件夹 zip.remove(oldFolderPath);
实用封装工具函数
如果需要多次操作,可以封装成通用函数,同时兼容文件和文件夹:
function renameZipEntry(zip, oldPath, newPath) { const entry = zip.file(oldPath) || zip.folder(oldPath); if (!entry) return Promise.reject(new Error("目标条目不存在")); if (entry.dir) { // 处理文件夹 entry.forEach((relPath, file) => { zip.file(`${newPath}/${relPath}`, file); }); zip.remove(oldPath); return Promise.resolve(); } else { // 处理文件 return entry.async("arraybuffer").then(content => { zip.file(newPath, content); zip.remove(oldPath); }); } } // 使用示例 renameZipEntry(zip, "oldFolder", "newFolder") .then(() => console.log("重命名完成")) .catch(err => console.error(err));
注意事项
- 若新路径包含多级目录(如
docs/newfile.txt),JSZip会自动创建不存在的目录,无需手动创建文件夹。 - 处理二进制文件(图片、压缩包等)时,务必用
async("arraybuffer")获取内容,避免文本编码导致内容损坏。
内容的提问来源于stack exchange,提问作者noname
相关产品推荐
相关产品推荐

