【问题标题】:Allow user to upload JSON, then use the JSON to render the page允许用户上传 JSON,然后使用 JSON 渲染页面
【发布时间】:2021-08-03 07:13:17
【问题描述】:

目前在我的网站上,我允许用户将 JSON 数据粘贴到 HTML 表单中,然后我使用 JSON 数据来更改页面的呈现。如何用文件上传功能替换表单?我不需要将数据存储在 Web 服务器上。只要这一切都在浏览器中运行就可以了。我的网站是用 PHP 编写的。谢谢。

【问题讨论】:

  • 使用file_get_contents($_FILES['name']['tmp_name']),其中name是<input type="file">的名称
  • 代替$_POST['textarea_name']
  • 这一切都可以在浏览器中完成,但这是否容易取决于数据的结构和页面的构建方式。它的优点是不需要重新加载页面。你能发布一个页面源和 JSON 数据的简单示例吗?
  • @Barmar - 你的例子是使用 jquery 吗?我目前没有使用 jquery。
  • 我的 cmets 是 PHP,不是 JavaScript。

标签: php html json upload


【解决方案1】:

这是一个简单的演示程序,它会提示用户输入文件、读取文件并将内容发布到<textarea>。它还将 JSON 内容解析为变量并将其发送到console.log。从这里您应该能够解压缩数据并更新您的页面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Reader Demo</title>
</head>
<body>
<form id="fileForm">
    <input type="file" name="fileItem" id="fileItem" required>
    <input type="submit">
</form>
<textarea id="fileContents"></textarea>
<script>
    (function(){
        "use strict";
        // Add an event handler to the form's submit event
        document.getElementById('fileForm').addEventListener('submit', function(e){
            // Stop the browser submitting anything
            e.preventDefault();
            // Get the file object
            let file = document.getElementById('fileItem').files[0];
            // Check the file is actually JSON
            if (file.type !== "application/json") {
                document.getElementById('fileContents').value = "Invalid file type"+file.type;
            } else {
                // Create a file reader
                let reader = new FileReader();
                // Add an event handler to the 'load' event
                reader.addEventListener('load', function (e) {
                    // Post the file contents to the page
                    document.getElementById('fileContents').value = e.target.result;
                    // parse the JSON
                    let jsonData = JSON.parse(e.target.result);
                    // Process incoming JSON data here.
                    console.log(jsonData);
                })
                // Read the file as text. We'll parse it with JSON.parse later
                reader.readAsText(file);
            }
        })
    })();
</script>
</body>
</html>

【讨论】:

  • 啊哈!不确定服务器端脚本是否需要访问传输文件的内容。此功能是在以后的某个日期(例如最近)添加到 JavaScript 中的吗?
  • 根据caniuse.com,FileReader API 于 2010 年开始出现,并在 2012 年得到所有主要浏览器的支持。我不确定它是否符合“最近”的条件。
  • 是的,对我来说这是最近的事,哈哈!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多