在Web应用中向IPFS上传文件
- 原文: https://dev.to/dabit3/uploading-files-to-ipfs-from-a-web-application-50a 作者:Nader Dabit
- 译文出自:登链翻译计划
- 译者:翻译小组
- 校对:Tiny 熊
- 本文永久链接:learnblockchain.cn/article…
与IPFS的交互最常见的方式是从客户端应用程序上传图片和视频等文件,但我发现,好像没有很直接明了的教程。
在本教程中,你将通过使用ipfs-http-client,以尽可能少的代码(尽可能简单)来学习。这里的想法是在React中实现的,但应该可以相当容易地转移到任何其他JavaScript框架中,如Vue、Angular或Svelte。
IPFS是一个去中心化的、点对点的文件共享协议。
有各种类型的IPFS网关可用,有些是免费的,有些则不是。有些提供只读访问,有些则提供读写访问。
你也可以运行你自己的IPFS网关。
因为我们将上传/保存文件,需要选择一个允许我们写访问的网关,这里使用的网关是Infura,其他流行的服务网管有Pinata或Fleek。
关于如何用Pinata将文件pin在IPFS上的例子,请查看这个代码库。
如果你已经创建了一个React应用程序,则可以跳过这个步骤。
首先,创建一个新的React应用程序,并进入新目录。
npx create-react-app ipfs-example
cd ipfs-example接下来,使用NPM或Yarn安装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 赞助支持。
 
                如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!