vue 处理JSON文件——上传导入、下载导出、在线预览

该博客详细介绍了如何在前端实现JSON文件的上传、在线预览及导出功能。通过使用Element UI组件库,演示了文件上传的限制、文件格式检查、文件读取及内容展示。同时,还展示了使用file-saver插件实现JSON文件的下载功能。
摘要由CSDN通过智能技术生成

上传导入JSON文件

在这里插入图片描述

<el-button @click="importData" size="mini">导入</el-button>
  data() {
    return {
      fileList: [],
      uploadData: [],
      dialogImport: false,
    importData() {
      this.dialogImport = true;
    },
   <el-dialog
      :visible.sync="dialogImport"
      title="导入"
      v-if="dialogImport"
      width="40%"
      append-to-body
    >
      <div style="text-align:center">
        <!-- 此处action需为有效的任意接口——当前为官网范例接口 -->
        <el-upload
          drag
          :limit="1"
          action="https://jsonplaceholder.typicode.com/posts/"
          ref="upload"
          accept=".json"
          :file-list="fileList"
          :on-success="onSuccess"
          :on-remove="onRemove"
          :on-exceed="handleExceed"
          :on-preview="handlePreview"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            上传json文件,且只能上传 1 个文件
          </div>
        </el-upload>
      </div>
      <span slot="footer">
        <el-button @click="dialogImport = false" size="mini">取 消</el-button>
        <el-button @click="importConfirm" size="mini" type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    // 上传文件超出文件数量限制/文件格式不符合要求时
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能导入一个json文件!`);
    },

    // 文件上传成功
    onSuccess(res, file, fileList) {
      let reader = new FileReader();
      reader.readAsText(file.raw);
      reader.onload = (e) => {
        this.uploadData = [];
        this.uploadData = JSON.parse(e.target.result);
      };
    },

    // 移除文件
    onRemove(file) {
      this.fileList = [];
    },

    // 导入确认
    importConfirm() {
      this.$confirm("导入后原数据会被覆盖,确定导入吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
      // 使用目标数据变量接收上传后的文件数据
        this.stockData = this.uploadData;

        this.dialogImport = false;

        this.$message({
          type: "success",
          message: "导入成功!",
        });
      });
    },

在线预览JSON文件

续上例,上传文件后,点击文件名打开预览弹窗
在这里插入图片描述
在这里插入图片描述

      jsonData: null,
      dialogPreviewJSON: false,
    handlePreview(file) {
      let reader = new FileReader();
      reader.readAsText(file.raw);
      reader.onload = (e) => {
        this.jsonData = JSON.parse(e.target.result);
        this.dialogPreviewJSON = true;
      };
    },
    <el-dialog
      :visible.sync="dialogPreviewJSON"
      title="JSON文件预览"
      v-if="dialogPreviewJSON"
      width="40%"
      append-to-body
    >
      <s-json :json="jsonData"></s-json>
    </el-dialog>

s-json.vue组件

<template>
  <div>
    <pre v-html="formattedJSON"></pre>
  </div>
</template>
<script>
export default {
  props: {
    json: Object,
  },
  mounted() {
    this.formattedJSON = syntaxHighlight(this.json);
  },
  data() {
    return {
      formattedJSON: "",
    };
  },
};

function syntaxHighlight(json) {
  if (typeof json != "string") {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">");
  return json.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
    function(match) {
      var cls = "number";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "key";
        } else {
          cls = "string";
        }
      } else if (/true|false/.test(match)) {
        cls = "boolean";
      } else if (/null/.test(match)) {
        cls = "null";
      }
      return '<span class="' + cls + '">' + match + "</span>";
    }
  );
}
</script>
<style scoped>
/deep/ pre {
  outline: 1px solid #ccc;
  padding: 5px;
  margin: 5px;
}

/deep/ .string {
  color: green;
}

/deep/ .number {
  color: darkorange;
}

/deep/ .boolean {
  color: blue;
}

/deep/ .null {
  color: magenta;
}

/deep/ .key {
  color: red;
}
</style>

下载导出JSON文件

会下载到浏览器默认的下载位置,无法统一指定下载的路径。
在这里插入图片描述
需安装插件 file-saver

npm install file-saver --save

vue文件中

// 插件 -- 下载文件
import FileSaver from "file-saver";
<el-button @click="exportData" size="mini">导出</el-button>
    exportData() {
      let data = JSON.stringify(this.stockData);
      let blob = new Blob([data], { type: "application/json" });
      FileSaver.saveAs(blob, `股票数据.json`);
    },
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值