从 Web 应用程序上传文件到 IPFS
与IPFS最常见的交互之一是从客户端应用程序上传图像和视频等文件,因此我发现没有很多简单的教程展示如何做到这一点,这让我感到惊讶。
在本教程中,你将使用尽可能少的代码行(并且尽可能简单)来学习这一点ipfs-http-client
。这里的想法是在 React 中实现的,但应该可以很容易地转移到任何其他 JavaScript 框架(例如 Vue、Angular 或 Svelte)中执行相同的操作。
关于IPFS
IPFS 是一种去中心化的、点对点的文件共享协议。
市面上有各种类型的IPFS 网关。有些是免费的,有些则需要。有些提供只读访问权限,有些则同时提供读写访问权限。
您还可以运行自己的 IPFS 网关。
因为我们要上传/保存文件,所以我们需要确保选择一个允许写入权限的网关。今天我们将使用的网关是Infura。其他流行的服务包括Pinata或Fleek。
为了使此示例正常工作,您需要注册Infura并获取项目 ID 和 API 密钥。
有关如何使用 Pinata 将文件固定到 IPFS 的示例,请查看此 repo。
入门
如果您已经创建了 React 应用程序,则可以跳过此步骤。
首先,创建一个新的 React 应用程序并进入新目录:
npx create-react-app ipfs-example
cd ipfs-example
接下来,使用NPM或Yarnipfs-http-client
安装库:buffer
npm install ipfs-http-client buffer
基本代码
这些代码行可以概括基本功能,但我还将构建整个 UI 来展示它们如何组合在一起。
实现此功能的基本代码如下:
/* import the ipfs-http-client and buffer libraries */
import { create } from 'ipfs-http-client'
import { Buffer } from 'buffer'
/* configure Infura auth settings */
const projectId = "<your-infura-project-id>"
const projectSecret = "<your-infura-project-secret>"
const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64')
/* Create an instance of the client */
const client = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
}
})
/* upload the file */
const added = await client.add(file)
/* or a string */
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'
import { Buffer } from 'buffer'
/* configure Infura auth settings */
const projectId = "<your-infura-project-id>"
const projectSecret = "<your-infura-project-secret>"
const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
/* create the client */
const client = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
})
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://infura-ipfs.io/ipfs/${added.path}`
updateFileUrl(url)
console.log("IPFS URI: ", url)
} catch (error) {
console.log('Error uploading file: ', error)
}
}
return (
<div className="App">
<h1>IPFS Example</h1>
<input
type="file"
onChange={onChange}
/>
{
fileUrl && (
<div>
<img src={fileUrl} width="600px" />
<a href={fileUrl} target="_blank">{fileUrl}</a>
</div>
)
}
</div>
);
}
export default App
接下来运行应用程序:
npm start
当应用程序加载时,您应该会看到一个文件上传按钮。
文件成功上传后,您应该会在 UI 中看到它。
鏂囩珷鏉ユ簮锛�https://dev.to/edge-and-node/uploading-files-to-ipfs-from-a-web-application-50a