在js-ipfs中通过哈希获取文件遇问题,寻求技术帮助
解决js-ipfs中
ipfs cat返回文件路径而非内容的问题 嘿,我看你遇到的问题是用js-ipfs上传文件后,调用ipfs cat只能拿到文件路径字符串,而不是实际的文件内容——这问题根源很明确:你上传到IPFS的根本不是文件内容,而是浏览器里显示的文件路径字符串!
问题出在哪?
你代码里用document.getElementById('fileInput').value获取的是浏览器出于安全策略返回的虚拟路径(比如C:\fakepath\your-file.txt),这只是个字符串,不是文件的二进制数据。所以IPFS存储的就是这个路径字符串,ipfs cat自然返回它了。
修复方案
我们需要正确获取文件对象,读取它的实际内容再上传,具体步骤如下:
- 从fileInput中获取真实的文件对象,而不是路径字符串
- 使用
FileReader读取文件的二进制内容 - 将读取到的内容转成js-ipfs需要的
Buffer类型再上传
修改后的完整代码
const node = new Ipfs() node.once('ready', () => console.log('IPFS node is ready')) $("#saveIt").click(function(){ // 获取选中的文件对象 const fileInput = document.getElementById('fileInput'); const selectedFile = fileInput.files[0]; if (!selectedFile) { console.error("请先选择一个文件"); return; } // 读取文件内容 const reader = new FileReader(); reader.onload = function(e) { // 将读取到的ArrayBuffer转成Buffer const fileContentBuffer = new node.types.Buffer.from(e.target.result); // 上传到IPFS node.files.add(fileContentBuffer, (err, res) => { if (err || !res) { return console.error('ipfs add error', err, res) } res.forEach((file) => { if (file && file.hash) { var newVar = file.hash var newVar1 = newVar.slice(0, 23) var leng = newVar.length var newVar2 = newVar.slice(24, leng) console.log(newVar1 + ' ' + newVar2) mediachain.setUserFile($("#passwordSetter").val(), newVar1, newVar2) // 读取IPFS上的文件内容 node.files.cat(file.hash, (err, data) => { if (err) { return console.error('ipfs cat error', err) } // 文本文件直接转字符串显示;二进制文件需额外处理(如转base64) document.getElementById('fileDisplayArea').innerText = data.toString() }) } else { console.error("Error: invalid file") } }) }); }; // 以ArrayBuffer格式读取文件 reader.readAsArrayBuffer(selectedFile); })
关键改动说明
- 替换
fileInput.value为fileInput.files[0]:拿到真实的File对象,而不是虚拟路径字符串 - 新增
FileReader处理文件读取:浏览器读取文件是异步操作,需要通过onload回调获取内容 - 将读取结果转成
node.types.Buffer:符合js-ipfs的上传数据格式要求 data.toString():针对文本文件的显示方式,如果是图片、视频等二进制文件,你需要转成base64或者用URL.createObjectURL来展示。
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

