使用NFT.Storage上传文件至IPFS失败问题求助
问题排查与修复方案
1. 核心代码语法/逻辑错误
你的upload.js存在两处致命问题,直接导致上传失败:
- 重复声明
metadata变量:调用client.store()后又用const重复定义同名变量,触发语法错误 - 未定义
blob变量:client.storeBlob(blob)中的blob从未创建,属于无效代码
修复后的upload.js核心代码:
router.post('/uploadToIPFS', upload.single('studentDocument'), async (req, res) => { const { originalname: fileName, path: tempFilePath, mimetype } = req.file; try { const fileData = await fs.readFile(tempFilePath); // 调用NFT.Storage存储文件与元数据 const metadata = await client.store({ name: req.body.name || 'File', description: req.body.description || 'description', image: new File([fileData], fileName, { type: mimetype }) }); const cid = metadata.ipnft.toString(); // 向客户端返回成功结果 res.status(200).json({ success: true, cid: cid, metadataUrl: `ipfs://${cid}` }); } catch (error) { // 打印完整错误详情,便于定位问题 console.error('IPFS上传错误详情:', error.message, error.stack); res.status(500).json({ error: 'IPFS上传失败', details: error.message }); } finally { await fs.unlink(tempFilePath); } })
2. 环境变量加载验证
确保NFT_STORAGE_API_TOKEN正确加载:
- 项目根目录创建
.env文件,写入NFT_STORAGE_API_TOKEN=你的实际API密钥 - 在代码顶部添加
require('dotenv').config()(需先安装依赖:npm install dotenv) - 可临时打印
console.log(process.env.NFT_STORAGE_API_TOKEN)确认密钥是否正常读取
3. 前端表单数据补充
当前前端仅上传文件,未传递name和description字段,若需这两个参数,需在表单中添加对应输入框:
<form id="documentUploadForm" enctype="multipart/form-data" class="d-flex justify-content-between gap-2"> <input type="text" name="name" placeholder="文件名称" class="form-control w-25"> <input type="text" name="description" placeholder="文件描述" class="form-control w-25"> <input type="file" name="studentDocument" class="form-control w-25 ps-2" style="height: 35px;"> <button type="submit" id="docUpload" class="btn btn-lg fw-bolder form-btn py-1 px-3 float-end">点击上传</button> </form>
4. 额外排查点
- 检查网络是否能正常访问NFT.Storage API(部分地区可能需要代理)
- 确认上传文件大小未超过平台限制(免费用户单文件最大1GB)
- 验证API密钥是否有效,可直接在NFT.Storage官网控制台测试密钥权限
内容的提问来源于stack exchange,提问作者Sadanand Miskin
相关产品推荐
相关产品推荐

