- 原生展示
<input type="file" ref="saveImage" />
<img src alt ref="abc" style="width: 200px; height:200px">
// js
great () {
this.$refs.saveImage.onchange = () => {
var imgFile = this.$refs.saveImage.files[0]
var fr = new FileReader()
fr.onload = () => {
this.$refs.abc.src = fr.result
}
fr.readAsDataURL(imgFile)
}
},
ElementUI组件展示
<el-upload
class="upload-demo"
ref="upload"
action="https://jsonplaceholder.typicode.com/posts/"
:file-list="fileList"
:show-file-list="false"
:on-change="changeHandle"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<ul style="margin: 12px 0; width: 70%">
<li v-for="(item,index) in fileList" :key="item.name">
<img :src="item.url" alt="">
<i class="el-icon-delete" @click="deleteItem(index)"></i>
<!-- <span>{{ item.name }}</span> -->
</li>
</ul>
</el-upload>
// js
export default {
data () {
return {
fileList: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }, { name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }]
}
},
methods: {
submitUpload () {
this.$refs.upload.submit()
},
changeHandle (file, fileList) {
const reader = new FileReader()
reader.readAsDataURL(file.raw)
reader.onload = () => {
fileList.forEach(item => {
if (item.name === file.name) {
item.url = reader.result
}
})
this.fileList = fileList
}
},
deleteItem (index) {
this.fileList.splice(index, 1)
}
}
}
将文件转换为base64