1、预先安装配置好IPFS
2、运行 ipfs help (如出现下图安装ipfs完成)
3、运行 ipfs daemon (出现下图表示成功)
4、利用vue创建一个项目
vue create ipfs
5、出现下列文件
6、在如下目录中
编写 IPFS.vue
<template>
<div class="home">
<el-container>
<el-form label-width="80px">
<el-form-item label="产品图片">
<div class="img-wrapper">
<img class="img-panel" :src="photoURL1" />
<div class="txt-title">{{ipfsHash}}</div>
</div>
<el-upload class="img-upload" action="tmp" :limit="1" :on-change="handleChange"
:on-exceed="handleExceed" :auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="uploadImage">
上传到服务器
</el-button>
</el-upload>
<el-input v-model="photoURL1"></el-input>
</el-form-item>
</el-form>
</el-container>
</div>
</template>
<script>
import { create } from 'ipfs-http-client'
import Buffer from "vue-buffer";
export default {
data() {
const ipfs = create('http://192.168.1.161:5001/')
return {
photoURL1: '',
fileList: [],
ipfs: ipfs,
buffer: null,
ipfsHash: ''
};
},
mounted() {
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList;
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
uploadImage() {
if (this.fileList.length < 1) {
this.$message.warning('请选择需要上传的文件')
} else {
const reader = new window.FileReader()
console.log(this.fileList[0].raw)
reader.readAsArrayBuffer(this.fileList[0].raw)
reader.onloadend = () => {
this.buffer = Buffer(reader.result)
this.uploadToIPFS()
}
}
},
async uploadToIPFS() {
let result = await this.ipfs.add(this.buffer)
console.log(result)
this.photoURL1 = `https://ipfs.io/ipfs/${result.path}`
this.ipfsHash = `${result.path}`;
},
},
};
</script>
<style>
body>.el-container {
margin-bottom: 40px;
}
.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
line-height: 260px;
}
.el-container:nth-child(7) .el-aside {
line-height: 320px;
}
</style>
7、修改 App.vue 代码如下
<template>
<div id="app">
<IPFS/>
</div>
</template>
<script>
import IPFS from './components/IPFS.vue'
export default {
name: 'App',
components: {
IPFS
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
8、修改 main.js 如下
import Vue from 'vue'
import App from './App.vue'
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
Vue.use(ElementUI);
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
~
9、由于用到了element ui,所以需要下载依赖
npm install element-ui --save
10、下载依赖
npm install --save vue-buffer
11、在node_modules所在目录可以启动程序
npm run serve
页面如下:
标签:el,IPFS,vue,文件系统,fileList,result,Vue2,ipfs,import From: https://blog.51cto.com/u_15738297/6140249