Write the Code. Change the World.

6月 17

这里就是尝试下 web3.storage,尝试 ipfs。

注册并取得 token

https://web3.storage/

去上边地址注册个账号。使用 github 授权或自己的 email 都可以。

点击 Account -> Create an Api Token 创建一个 token。你可以在 Api Tokens 里边里看见你创建的 token。

每个注册用户将会拥有 1 TiB 的空间。

尝试上传文件

不用 sdk,使用官网的 ui 界面,尝试上传文件。

打开首页,点击 START STORING NOW 按钮,再点击右侧的 Upload Files 。点击弹窗的虚线框内或拖动文件进虚线框内都可。

上传成功后,在文件列表里,就可以看见刚上传的文件了。 记住 CID, 你就不会丢失你的文件。要 pin 到链上才是最终的不会丢失。

使用 node.js 调用 sdk 上传

  • 先初始化一个 node 项目
    打开终端(mac 用 iterm2)
# 输入下边的类容回车。遇到输入时,输入你想输入的内容即可。一路疯狂回车,就好。
npm init 

最后,会创建一个 package.json。内容如下:

{
  "name": "webstorage",
  "version": "1.0.0",
  "description": "webstorage study",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "web3.0",
    "storage",
    "ipfs"
  ],
  "type": "module",
  "author": "vini123",
  "license": "ISC",
  "dependencies": {
  }
}

注意, "type": "module" 是后来添加的。加了这个,node 运行的时候才不会以 CommonJS 方式运行,以 ES Modules 方式运行 。这个很重要。可以看看下边的文章了解一下下。
https://zhuanlan.zhihu.com/p/179038296

  • 安装 web3.storage sdk 和 minimist
npm install minimist
npm install web3.storage
  • 新建一个 index.js 文件输入以下代码
mport process from 'process'
import minimist from 'minimist'
import { Web3Storage, getFilesFromPath } from 'web3.storage'

async function main () {
  const args = minimist(process.argv.slice(2))
  const token = args.token

  if (!token) {
    return console.error('A token is needed. You can create one on https://web3.storage')
  }

  if (args._.length < 1) {
    return console.error('Please supply the path to a file or directory')
  }

  const storage = new Web3Storage({ token })
  const files = []

  for (const path of args._) {
    const pathFiles = await getFilesFromPath(path)
    files.push(...pathFiles)
  }

  console.log(`Uploading ${files.length} files`)
  const cid = await storage.put(files)
  console.log('Content added with CID:', cid)
}

main()

好了,下边在终端中输入以下命令:

node index.js --token=xxxx ~/file1

成功后,返回下边这样的结果:

Uploading 1 files
Content added with CID: xxxybeiaicsg3xkhcnxnh5tmgefq54l7fgxxj5ksfl2duo2ji4dlmhbr2la

你有了 cid 后,就可以通过下边链接看见文件:https://dweb.link/ipfs/cid 。记得将末尾的 cid 替换成你上传文件后得到的 cid 。

参考

https://web3.storage/docs/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注