【问题标题】:Vue upload local json filevue上传本地json文件
【发布时间】:2020-03-28 01:30:49
【问题描述】:

我找不到我的问题的答案,我认为只有 Vue.js 才有可能,但我不能 100% 确定。所以问题是这样的。我希望用户从他的计算机中选择文件,它总是 json 文件。可以仅使用 Vue.js 获取该文件并使用它,或者我需要一些后端。

【问题讨论】:

  • 这里确实没有特别需要vue。您可以使用带有type=file 属性和limit input types 的HTML5 <input> 标签。不,不需要后端服务在您的代码中上传文件。
  • 可能在客户端是:选择文件,将其限制为唯一的 JSON。然后,您可能需要后端:具有端点的服务器,您可以将文件上传到该服务器,并且可以稍后访问它以进行某些处理。对于后端,您还可以使用其他一些服务,例如 firebase、s3 等......它们会提供一个 API,您可以在其中发送您的 JSON 文件。
  • @ShivamSingh - 绝对不需要任何后端

标签: json file vue.js import vue-component


【解决方案1】:

这里没有 Vue 特有的东西,也不需要服务器。

方法是使用特殊的<input type="file">FileReader()

document.getElementById('import').onclick = () => {
  const files = document.getElementById('selectFiles').files;
  if (files.length <= 0) {
    return false;
  }

  const fr = new FileReader();

  fr.onload = e => {
    const result = JSON.parse(e.target.result);
    const formatted = JSON.stringify(result, null, 2);
    document.getElementById('result').innerHTML = formatted;
  }
  fr.readAsText(files.item(0));
};
<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import The File!</button>
<pre id="result"></pre>

显然,这段代码可以很容易地在 Vue 应用中实现。

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2011-12-05
    相关资源
    最近更新 更多