Next.js中从URL拉取图片上传至IPFS报错如何解决
问题诊断
你代码的核心问题有两处:
- Axios请求的
then回调中没有返回构造好的File对象,导致你声明的file变量最终值为undefined,IPFS客户端接收空输入时就会抛出你看到的Unexpected input: undefined错误。 - 当前Infura的公共IPFS节点已不再支持无密钥访问,基础问题修复后你还需要在Infura后台创建IPFS项目,将项目ID和密钥填入
ipfs-http-client的初始化配置中才能正常使用服务。
修复后的代码
/* pages/test.js */ import Axios from 'axios'; import { create } from 'ipfs-http-client'; // 后续Infura鉴权用初始化方式,替换为你自己的项目ID和密钥即可 // const client = create({ // host: 'ipfs.infura.io', // port: 5001, // protocol: 'https', // headers: { // authorization: 'Basic ' + Buffer.from('<你的项目ID>:<你的项目密钥>').toString('base64'), // }, // }) const client = create('https://ipfs.infura.io:5001/api/v0'); export default function Test () { async function uploadImageToIPFS (url) { try { const response = await Axios.get(url, { responseType: 'blob' }) // 显式返回File对象并指定MIME类型 const file = new File([response.data], "dummy", { type: response.data.type }); const added = await client.add( file, { progress: (prog) => console.log(`received: ${prog}`) } ) const ipfsUrl = `https://ipfs.infura.io/ipfs/${added.path}`; console.log(ipfsUrl); } catch (error) { console.log('Error uploading file: ', error); } } return ( <div onClick={() => uploadImageToIPFS('https://media-exp1.licdn.com/dms/image/C4E03AQFDEyGQpYnEwA/profile-displayphoto-shrink_100_100/0/1572360635415?e=1635379200&v=beta&t=W3cLmvalBVyArWAwTnbyeEWrJNbc9eKT7IJgoPhO22w')}> Click to upload </div> ); }
补充说明
- 建议将Axios请求和IPFS上传逻辑放在同一个
try...catch块中,避免请求出错时后续逻辑依然执行的问题。 - 构造
File对象时传入type参数指定文件的MIME类型,可以方便IPFS网关识别文件格式。
内容的提问来源于stack exchange,提问作者Keir Finlow-Bates
相关产品推荐
相关产品推荐

