19

通过Web应用向IPFS上传文件

 4 years ago
source link: https://learnblockchain.cn/article/2952
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

通过Web应用向IPFS上传文件

在Web应用中向IPFS上传文件

IPFS的交互最常见的方式是从客户端应用程序上传图片和视频等文件,但我发现,好像没有很直接明了的教程。

在本教程中,你将通过使用ipfs-http-client,以尽可能少的代码(尽可能简单)来学习。这里的想法是在React中实现的,但应该可以相当容易地转移到任何其他JavaScript框架中,如Vue、Angular或Svelte。

关于IPFS

IPFS是一个去中心化的、点对点的文件共享协议。

有各种类型的IPFS网关可用,有些是免费的,有些则不是。有些提供只读访问,有些则提供读写访问。

你也可以运行你自己的IPFS网关

因为我们将上传/保存文件,需要选择一个允许我们写访问的网关,这里使用的网关是Infura,其他流行的服务网管有PinataFleek

关于如何用Pinata将文件pin在IPFS上的例子,请查看这个代码库

如果你已经创建了一个React应用程序,则可以跳过这个步骤。

首先,创建一个新的React应用程序,并进入新目录。

npx create-react-app ipfs-example

cd ipfs-example

接下来,使用NPMYarn安装ipfs-http-client库。

npm install ipfs-http-client

上传基本代码

基本功能只需3行代码就能概括,但我也将建立一个完整的用户界面,以显示它是如何组合在一起的。

可工作的基本代码:

/* import the ipfs-http-client library */
import { create } from 'ipfs-http-client';

/* 创建一个 IPFS 客户端实例 */
const client = ipfsHttpClient('https://ipfs.infura.io:5001/api/v0')

/* 上传文件 */
const added = await client.add(file)

/* 上传字符串 */
const added = await client.add('hello world')

完整的代码

现在让我们看看运用上述代码在应用程序中实际实现文件上传功能,以及查看图片。

在你的项目中,打开src/App.js,更新为以下代码:

/* src/App.js */
import './App.css'
import { useState } from 'react'
import { create } from 'ipfs-http-client'

const client = create('https://ipfs.infura.io:5001/api/v0')

function App() {
  const [fileUrl, updateFileUrl] = useState(``)
  async function onChange(e) {
    const file = e.target.files[0]
    try {
      const added = await client.add(file)
      const url = `https://ipfs.infura.io/ipfs/${added.path}`
      updateFileUrl(url)
    } catch (error) {
      console.log('Error uploading file: ', error)
    }  
  }
  return (
    <div className="App">
      <h1>IPFS Example</h1>
      <input
        type="file"
        onChange={onChange}
      />
      {
        fileUrl && (
          <img src={fileUrl} width="600px" />
        )
      }
    </div>
  );
}

export default App

接下来,运行该应用程序。

npm start

当应用程序加载时,你应该看到一个文件上传按钮。

一旦一个文件被成功上传,你应该看到它在用户界面上呈现出来。

你看, 超简单的。


本翻译由 CellETF 赞助支持。

本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

  • 发表于 23小时前
  • 阅读 ( 82 )
  • 学分 ( 12 )
  • 分类:IPFS

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK