Published: 17 Dec 2019 › Updated: 17 Dec 2019
上传图片到IPFS网络 / 网络研习社#53
在上一篇《零代码用IPFS做文件服务器》中启动了IPFS网络,这时服务器这边就准备好了,前端就可以向IPFS网络上传图片了。
关键的函数只有一个ipfs.add,前端读取图片,用ipfs.add上传,得到一个文件的哈希值,再在前端展示就好啰。
js-ipfs-http-client
- 前端和IPFS网络交互需要用到客户端插件
js-ipfs-http-client,一条命令就可以安装好,cnpm install ipfs-http-client --save - 必要的设置(vue中导入包,连接客户端)
import ipfsClient from 'ipfs-http-client'
const ipfs = ipfsClient({ host: 'localhost', port: '9000', protocol: 'http' })
- 前端代码
<label id="file2">Choose file to upload</label>
<input type="file" ref="file" id="file" name="file" multiple="multiple"/>
<input type="submit" @click="upload">
methods:{
upload() {
let that = this
let saveImageOnIpfs = (reader) => {
return new Promise(function(resolve, reject) {
const buffer = Buffer.from(reader.result)
that.ipfs.add(buffer).then((response) => {
console.log(response)
resolve(response[0].hash)
}).catch((err) => {
console.error(err)
reject(err)
})
})
}
let file = this.$refs.file.files[0]
console.log(123, file)
let reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend = function (e) {
console.log(233, reader)
saveImageOnIpfs(reader).then((hash) => {
console.log(655, hash)
})
}
}
}
上传图片就这么几行代码就可以搞定,比起PHP等来还是有一定的优势,至少看起来简单。再说,IPFS和区块链连接紧密,是天生的盟友,比如Steem 和IPFS和结合就可以开发出不错的应用来,星空笔记就不错!
Leave 上传图片到IPFS网络 / 网络研习社#53 to:
Read more #steemjiang posts
Best Posts From lemooljiang
We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From lemooljiang
- DeepTutor:AI个性化辅导平台 / ai #57
- ComfyUI:可编程和自动化的PS / ai #56
- 将Neo4j封装进Agent / ai #55
- 闲鱼省钱大法:极限0.5折!
- 对Neo4j批量导入结构化数据 / ai #54
- langchain对neo4j进行交互,写入和查询数据 / ai #53
- 知识图谱和图数据库Neo4j的作用和使用场景 / ai #52
- SpaceX、美股和比特币
- 又是币圈血洗日!
- 链股合流,当币安也开始卖股票啰
- 天涯社区重启,爷青回?
- 诺基亚在AI时代重新杀回来啦
- 《2049:未来10000天的可能》书中的镜像世界为什么不叫元宇宙
- 今天适合吃披萨
- 开通即被封,别再给Claude送人头了!
- 两根内存条引发的“官司”
- AI·Joe V12更新, 更新GPT-5.5和DeepSeek V4 等
- 中医进校园活动反响热烈
- 猪价低伤农,猪价贵伤民
- Solidity开发指南