2 Star 5 Fork 1

月下云生 / vue3learn

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
FilesOpera.vue 2.94 KB
一键复制 编辑 原始数据 按行查看 历史
月下云生 提交于 2023-04-10 19:00 . 注释
<template>
<div class="loginContainer">
<el-button plain type="text" style="position:absolute;left:20px;top:20px;font-size:18px;"
@click="back">返回</el-button>
<div class="formBOX">
<div style="font-weight:600;font-size:24px;margin-bottom:20px;">浏览器api操作本地文件</div>
<el-button type="primary" @click="importFile">读取图片</el-button>
<el-button type="primary" @click="importFiles">读取txt</el-button>
<div style="margin-top:20px;">
<div v-if="imgList.length > 0">
图片: <el-image v-for="item in imgList" :src="item" alt="" style="width:200px;" />
</div>
<div v-if="fileContent.length > 0" style="margin-top:20px;vertival-align:top;">
文字:<div style="width:75%;display:inline-block;">{{ fileContent }}</div>
</div>
</div>
</div>
<div style="返回数据"></div>
</div>
</template>
<!-- 浏览器api操作本地文件 -->
<script lang="ts" setup>
// showDirectoryPicker getDirectoryHandle getFileHandle removeEntry
import { ref } from 'vue'
const imgList: any = ref([])
const fileContent = ref('')
const importFile = async () => {
imgList.value = []
const arrFileHandle = await window.showOpenFilePicker({
types: [{
accept: {
'image/*': ['.png', '.gif', '.jpeg', '.jpg', '.webp']
}
}],
// 可以选择多个图片
multiple: true
});
// 遍历选择的文件
for (const fileHandle of arrFileHandle) {
// 获取文件内容
const fileData = await fileHandle.getFile();
console.log(fileData);
// 读文件数据
const buffer = await fileData.arrayBuffer();
// 转成Blod url地址
let src = URL.createObjectURL(new Blob([buffer]));
// 在页面中显示
imgList.value.push(src)
}
}
const importFiles = async () => {
try {
const hFiles = await window.showOpenFilePicker({
types: [
{
description: "文本文件",
accept: {
"text/plain": [".txt"],
},
},
],
});
if (!hFiles || !hFiles.length) return;
const hFile = hFiles[0]
const file = await hFile.getFile();
const r = new FileReader();
r.readAsText(file);
r.onload = (e) => {
const fileData:any = e.target!.result;
fileContent.value = fileData
}
} catch (error) {
console.error(error);
}
}
const back = async () => {
window.history.back()
}
</script>
<style lang="scss" scoped>
.loginContainer {
height: 100vh;
width: 100vw;
padding: 60px;
cursor: pointer;
box-sizing: border-box;
}
.loginTitle {
margin: 20px auto;
}
.formBOX {
width: 80%;
}
</style>
JavaScript
1
https://gitee.com/yuexiayunsheng/vue3learn.git
git@gitee.com:yuexiayunsheng/vue3learn.git
yuexiayunsheng
vue3learn
vue3learn
master

搜索帮助