Element-UI中Upload上传文件前端缓存处理

本文介绍如何使用Element-UI的文件上传组件在不上传文件到服务器的情况下,读取本地JSON文件并进行前端处理的方法。通过禁用自动上传模式,利用HTML5的FileReader API读取文件内容并解析为JSON格式。

Element-UI对于文件上传组件的功能点着重于文件传递到后台处理,所以要求action为必填属性。
但是如果需要读取本地文件并在前端直接处理,文件就没有必要传递到后台,比如在本地打开一个JSON文件,利用JSON文件在前端进行动态展示等等。
下面就展示一下具体做法:
首先定义一个jsonContent, 我们的目标是将本地选取的文件转换为JSON赋值给jsonContent
然后我们的模板文件是利用el-dialog和el-upload两个组件组合:这里停止文件自动上传模式:auto-upload="false"

 <el-button type="primary" @click="dialogVisible = true">Load from File</el-button>
  <el-dialog title="Load JSON document from file" :visible.sync="dialogVisible">
    <el-upload :file-list="uploadFiles" action="alert" :auto-upload="false" multiple :on-change="loadJsonFromFile">
      <el-button size="small" type="primary">Select a file</el-button>
      <div slot="tip">upload only jpg/png files, and less than 500kb</div>
    </el-upload>
    <span slot="footer">
      <el-button type="primary" @click="dialogVisible = false">cancel</el-button>
      <el-button type="primary" @click="loadJsonFromFileConfirmed">confirm</el-button>
    </span>
  </el-dialog>

最后通过html5的filereader对变量uploadFiles中的文件进行读取并赋值给jsonContent

if (this.uploadFiles) {
        for (let i = 0; i < this.uploadFiles.length; i++) {
          let file = this.uploadFiles[i]
          console.log(file.raw)
          if (!file) continue
          let reader = new FileReader()
          reader.onload = async (e) => {
            try {
              let document = JSON.parse(e.target.result)
              console.log(document)
            } catch (err) {
              console.log(`load JSON document from file error: ${err.message}`)
              this.showSnackbar(`Load JSON document from file error: ${err.message}`, 4000)
            }
          }
          reader.readAsText(file.raw)
        }
      }

为方便测试,以下是完整代码:

<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">Load from File</el-button>
  <el-dialog title="Load JSON document from file" :visible.sync="dialogVisible">
    <el-upload :file-list="uploadFiles" action="alert" :auto-upload="false" multiple :on-change="loadJsonFromFile">
      <el-button size="small" type="primary">Select a file</el-button>
      <div slot="tip">upload only jpg/png files, and less than 500kb</div>
    </el-upload>
    <span slot="footer">
      <el-button type="primary" @click="dialogVisible = false">cancel</el-button>
      <el-button type="primary" @click="loadJsonFromFileConfirmed">confirm</el-button>
    </span>
  </el-dialog>
</div>
 
</template>
 
<script>
export default {
  data () {
    return {
      // data for upload files
      uploadFilename: null,
      uploadFiles: [],
      dialogVisible: false
    }
  },
  methods: {
    loadJsonFromFile (file, fileList) {
      this.uploadFilename = file.name
      this.uploadFiles = fileList
    },
    loadJsonFromFileConfirmed () {
      console.log(this.uploadFiles)
      if (this.uploadFiles) {
        for (let i = 0; i < this.uploadFiles.length; i++) {
          let file = this.uploadFiles[i]
          console.log(file.raw)
          if (!file) continue
          let reader = new FileReader()
          reader.onload = async (e) => {
            try {
              let document = JSON.parse(e.target.result)
              console.log(document)
            } catch (err) {
              console.log(`load JSON document from file error: ${err.message}`)
              this.showSnackbar(`Load JSON document from file error: ${err.message}`, 4000)
            }
          }
          reader.readAsText(file.raw)
        }
      }
      this.dialogVisible = false
    }
  }
}
</script>

PS: 相关阅读

https://developer.mozilla.org...

作者:java_augur
来源:优快云
原文:https://blog.youkuaiyun.com/java_au...
版权声明:本文为博主原创文章,转载请附上博文链接!

### Element UI `el-upload` 实现文件删除功能 当使用 `el-upload` 组件时,可以通过监听 `file-list` 的变化来管理已上传文件列表,并通过自定义按钮或其他交互方式触发文件移除操作。为了实现这一目标,可以利用 `on-remove` 事件处理函数,在其中编写逻辑以真正从服务器端或本地存储中删除对应的文件。 下面是一个简单的 Vue.js 示例,展示了如何配置并实现带有删除功能的 `el-upload`: ```html <template> <div class="upload-demo"> <!-- 设置 :auto-upload=false 来禁用自动上传 --> <el-upload action="#" list-type="picture-card" :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="fileList" > <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt /> </el-dialog> <button @click="submitUpload">提交</button> <!-- 手动上传按钮 --> </div> </template> <script> export default { data() { return { fileList: [], // 文件列表 dialogImageUrl: '', dialogVisible: false, }; }, methods: { handleRemove(file, fileList) { // 处理文件移除事件 console.log('File removed:', file); // 如果需要向服务端发送请求,则在此处发起 AJAX 请求 this.fileList = fileList; // 更新文件列表状态 }, handlePictureCardPreview(file) { // 图片预览回调 this.dialogImageUrl = file.url; this.dialogVisible = true; }, submitUpload() { // 提交上传方法 const formData = new FormData(); this.fileList.forEach((item) => { formData.append('files', item.raw); // 将选中的文件加入到表单数据对象里 }); axios.post('/api/upload', formData).then(response => { alert('Files uploaded successfully!'); }).catch(error => { console.error('Error uploading files.', error); }); } } }; </script> ``` 此代码片段展示了一个基本的例子,其中包括了图片卡片形式(`list-type="picture-card"`), 并允许用户点击加号图标选择要上传文件[^2]。 当选择了某个文件之后会显示在界面上作为待上传项;而一旦调用了 `remove` 方法就会触发相应的钩子函数 (`handleRemove`) 进行进一步的操作,比如实际地清除缓存或者通知后台撤销该条目等动作[^3]。 得注意的是,如果希望阻止默认行为(即不立即更新视图),可以在 `handleRemove()` 中返回 `false` 或者调用参数里的 `done(false)` 函数[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值