前端文件读取与下载文件

402 阅读1分钟

项目介绍

项目环境:Vue、TypeScript、elementUI Plus

文件上传/读取

<script lang="ts" setup>
//上传文件
const content = ref(''),
  fileName = ref('')
const loadTextFile = (e: any) => {
  const file = e.target.files[0]
  //可以打印看一下file对象里面的内容
  const reader = new FileReader()
  reader.onload = function fileReadCompleted() {
    content.value = (reader.result as string) || ''
  }
  fileName.value = file.name
  language.value = file.name.slice(-4)
  reader.readAsText(file)
}
</script>
<template>
    <label>
       <!-- 不使用原生input组件的样式,重新写一个span -->
       <span class="text_style">
          {{ fileName.length > 0 ? '重新上传' : '上传文件' }}
        </span>
        <input type="file" style="display: none" @change="loadTextFile" />
    </label>
</template>
<style lang="scss" scoped>
.text_style {
    display: inline-block;
    width: 88px;
    height: 32px;
    cursor: pointer;
    text-align: center;
    line-height: 32px;
    border-radius: 4px;
    border: 1px solid #d7dae2;
  }
</style>

关于FileReaderAPI:developer.mozilla.org/zh-CN/docs/…

文件下载

<script lang="ts" setup>
const content = ref('{"text":"1"}'),
  handleDownLoad = () => {
    const blob = new Blob([content]) //content为需要下载内容
    const objectURL = URL.createObjectURL(blob)
    const aTag = document.createElement('a')
    // 设置文件的下载地址
    aTag.href = objectURL
    // 设置保存后的文件名称
    aTag.download = route.query.id + '.' + language.value
    // 给 a 标签添加点击事件
    aTag.click() 
    URL.revokeObjectURL(objectURL) //释放引用
  }
</script>
<template>
    <v-button type="text" @click="handleDownLoad">
        下载文件
    </v-button>
</template>

关于BlobAPI:developer.mozilla.org/en-US/docs/…

Bingo🎉🎉🎉