el-upload上传读取文件内容

在这里插入图片描述
在这里插入图片描述

<div>
   <div class="file-block">
     <div class="upload-block" v-if="!uploadSuccess">
        <el-upload v-model="ruleForm.customRules"  
                   :action="action" 
                   :limit="1" 
                   :before-upload="beforeUpload" 
                   :on-success="uploadSuccess" 
                   :file-list="fileList">
         <el-button class="upload">点击上传</el-button>
       </el-upload>
     </div>
     <div class="file" v-if="uploadSuccess">
       <span class="file-name">{{jsonfileName}}</span>
       <el-button type="text" @click="delJSON">删除</el-button>
     </div>
     <el-button type="text" @click="download">下载模板</el-button>
   </div>
  <div class="el-upload__tip">上传大小限制64kb,文件内容为JSON格式</div>
</div>
<script>
export default {
  data () {
    return {
      ruleForm:{
        customRules:'',//需提交的值
      },
      action:'……',//上传文件的地址
      fileList:'',
      uploadSuccess:false,
      jsonfileName:''//文件名
    }
  },
  methods:{
    //上传限制
    beforeUpload(file){
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType==='.json'||fileType==='.JSON') {
      }else{
        this.$message.error('暂不支持该文件格式');
        return false
      }
      if (file.size/1024>64) {
	    this.$message.error("文件不能大于64kb")
		return false
	  }
    },
    //上传成功读取文件
    uploadSuccess(res,file){
      this.jsonfileName=file.name
      this.uploadSuccess=true
      let val=''
      let reader=new FileReader();
      reader.readAsText(file.raw,'UTF-8')//读取,转换字符编码
      let vm=this
      reader.onload=function(e){
        val=e.target.result;//获取数据
        if(vm.checkJSON(val)){
          vm.uploadSuccess=true
          vm.ruleForm.customRules=val
        }else{
          vm.uploadSuccess=false
          vm.ruleForm.customRules=''
          vm.$message.error("JSON格式不符合规范");
        }
      }
      if (this.ruleForm.customRules) {
        this.$nextTick(()=>{
          this.$refs.ruleForm.clearValidate(["customRules"]);
        })
	  }
    },
    //try……cache与JSON.parse()校验JSON格式
    checkJSON(val){
      if(val){
         try {
            JSON.parse(val);
            return true;
        } catch(e) {
            return false;
        }
      }
    },
    //删除文件
    delJSON(){
      this.uploadSuccess=false
      this.ruleForm.customRules=''
    },
    //下载模板
    download(){
      let obj = {
        value1: 'value1',
        value2: 'value2'
      }
      let model=JSON.stringify(obj)
      const blob = new Blob([model], { type: "application/json;charset=utf-8" });
      const href = URL.createObjectURL(blob);
      const alink = document.createElement("a");
      alink.style.display = "none";
      alink.download = "模板.json";
      alink.href = href;
      document.body.appendChild(alink);
      alink.click();
      document.body.removeChild(alink);
      URL.revokeObjectURL(href);
    }
  }
}
### 使用 `el-upload` 组件上传 Excel 文件 #### 前端 Vue 页面设置 为了使用 `el-upload` 组件来上传 Excel 文件,在前端页面中可以按照如下方式定义该组件: ```html <template> <div> <!-- 定义 el-upload 组件 --> <el-upload ref="upload1" action="#" :limit="1" accept=".xls,.XLS,.xlsx,.XLSX" :auto-upload="false" :file-list="fileList" class="upload-formdata" @change="handleChange" > <el-button type="primary"> <i class="fa fa-upload"></i> 导入 </el-button> </el-upload> <!-- 提交按钮用于触发上传操作 --> <el-button type="success" @click="submitUpload">提交</el-button> </div> </template> <script> export default { data() { return { fileList: [], // 存储已选中的文件列表 }; }, methods: { handleChange(file, fileList) { this.fileList = fileList.slice(-1); // 只保留最新的一个文件 }, submitUpload() { const formData = new FormData(); if (this.fileList.length === 0) { alert('请选择要上传文件'); return; } formData.append('file', this.fileList[0].raw); fetch('/api/upload/excel', { // 后端API路径需根据实际情况调整 method: 'POST', body: formData, }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); } } }; </script> ``` 此部分代码展示了如何通过 `@change` 和自定义方法 `handleChange()` 来管理文件的选择状态,并利用表单数据对象 (`FormData`) 将选定的文件发送给服务器[^1]。 #### 后端接收逻辑 对于后端来说,当接收到带有 Excel 文件的数据请求时,应该能够正确解析并处理这些文件。这里给出 Python Flask 的简单例子作为说明: ```python from flask import request, jsonify import pandas as pd @app.route('/api/upload/excel', methods=['POST']) def upload_excel(): file = request.files.get('file') try: df = pd.read_excel(file.stream) excel_data_list = [] for index, row in df.iterrows(): record = {'手机号码': str(row['手机号码'])} excel_data_list.append(record) # 这里可以根据业务需求进一步处理excel_data_list return jsonify({ "status": "success", "message": f"{len(excel_data_list)} records processed.", "data": excel_data_list }), 200 except Exception as e: return jsonify({"error": str(e)}), 400 ``` 这段Python脚本实现了对接收的Excel文件读取以及转换成JSON格式返回的功能[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值