You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS客户端将已上传至w3storage的目录加入新目录且避免重复上传

解决方案

w3storage 内置功能说明

目前w3storage没有提供直接的“文件夹链接”或目录挂载功能,无法直接将已上传的文件夹关联到新目录下而不重新上传内容。要实现需求,只能通过创建包含指向原文件夹CID的新目录节点,并将这个节点打包成CAR文件上传的方式来模拟。

核心思路

IPFS中,目录本质是一个特殊的UnixFS节点,存储了子项名称与对应CID的映射。我们只需要创建一个新的目录节点,在其中添加指向原文件夹CID的条目,再将这个轻量的目录节点打包成CAR文件上传到w3storage,就能实现“在新目录中包含原文件夹”的效果,完全不需要重新上传原文件夹的内容。

JS 客户端实现步骤

1. 安装依赖

npm install @web3-storage/w3up-client ipfs-unixfs @ipld/car multiformats

2. 代码实现

import { create } from '@web3-storage/w3up-client'
import { UnixFS } from 'ipfs-unixfs'
import { CarWriter } from '@ipld/car'
import { CID } from 'multiformats/cid'
import { sha256 } from 'multiformats/hashes/sha2'
import * as raw from 'multiformats/codecs/raw'

async function createLinkedDirectory(existingFolderCID, newDirName, linkName) {
  // 解析原文件夹的CID
  const cid = CID.parse(existingFolderCID)

  // 创建新目录的UnixFS节点
  const dirFs = new UnixFS({ type: 'directory' })
  // 添加指向原文件夹的条目:名称为linkName,对应CID为原文件夹CID
  dirFs.addEntry({ name: linkName, cid })

  // 将目录节点序列化为IPLD区块
  const dirBytes = dirFs.marshal()
  const hash = await sha256.digest(dirBytes)
  const dirCID = CID.createV1(raw.code, hash)
  const block = { cid: dirCID, bytes: dirBytes }

  // 打包成CAR文件
  const { writer, out } = CarWriter.create([dirCID])
  writer.put(block)
  writer.close()

  // 收集CAR文件内容
  const carParts = []
  for await (const part of out) {
    carParts.push(part)
  }
  const carFile = new Blob(carParts, { type: 'application/vnd.ipld.car' })

  // 上传到w3storage
  const client = await create()
  // 需先完成客户端认证,比如通过client.login()或已保存的会话
  const uploadResult = await client.uploadFile(carFile, {
    name: `${newDirName}.car`
  })

  console.log(`新目录CID: ${uploadResult.cid}`)
  return uploadResult.cid
}

// 调用示例:原文件夹CID、新目录名称、新目录中原文件夹的显示名称
createLinkedDirectory(
  'bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
  'new-parent-directory',
  'my-existing-folder'
)

3. 关键说明

  • 上传的CAR文件仅包含新目录的节点数据,体积极小,不会重复上传原文件夹内容。
  • 访问新目录的CID时,会看到名为my-existing-folder的子目录,点击后直接指向原文件夹的内容。
  • 原文件夹的CID必须是已上传到w3storage且处于可访问状态的,否则新目录中的链接会失效。

内容的提问来源于stack exchange,提问作者ViteOrer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 22:04:57