使用javascript以字符串形式获取文件

get a file as a string using javascript

本文关键字:获取 文件 字符串 javascript 使用      更新时间:2023-09-26

我有一个HTML表单来上传文件。

我的目标是提交表单,检查文件是否具有XML扩展名,并将文件作为字符串获取到JavaScript变量中。

然后,我想用这个字符串向服务器发送一个POST请求。

知道我该怎么做吗?

我的目标是提交表单,检查文件是否具有XML扩展名,并将文件作为字符串获取到JavaScript变量中。

我不认为你真的想在这个阶段提交表单(比如,把它发送给服务器)。

然后,我想用这个字符串向服务器发送一个POST请求。

你可以在支持File API的浏览器上这样做,这是最现代的浏览器,但不是IE8或IE9。在这个答案中有一个例子。

基本上,您从<input type="file">元素的files列表中获得File实例,检查其名称,读取它,然后发布它:

完整的示例(源代码)(除了POST位,我假设您知道如何做):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
  <input type="file">
  <button>Go</button>
<script>
  (function() {
    "use strict";
    // Get our input element and our button; in this example there's
    // just one of each, you'd narrow down these selectors of course
    var inputElement = document.querySelector("input[type=file]"),
        button = document.querySelector("button");
    if (typeof FileReader !== 'function') {
      alert("The file API isn't supported on this browser.");
      inputElement.style.display = button.style.display = "none";
      return;
    }
    if (!inputElement.files) {
      alert("Odd, this browser has FileReader but no `files` property on the input element.");
      inputElement.style.display = button.style.display = "none";
      return;
    }
    button.addEventListener("click", function() {
      var file, filename, reader, filedata;
      // Does it have any files?
      if (inputElement.files.length === 0) {
        alert("No file chosen");
        return;
      }
      // Get its first file
      file = inputElement.files[0];
      // Get its name in lower case
      filename = file.name.toLowerCase();
      // XML extension?
      if (filename.substr(-4) !== ".xml") {
        alert("Please only choose .xml files");
      }
      else {
        // Yes, read it
        reader = new FileReader();
        reader.onload = function() {
          // Get the file data, note that this happens asynchronously
          filedata = reader.result;
          // Send your POST with the data; here, we'll just dump it out
          // as text
          displayXml(filedata);
        };
        reader.readAsText(file); // or you can use readAsBinaryString
      }
    }, false);
    function displayXml(xmlText) {
      var pre = document.createElement('pre');
      pre.innerHTML = xmlText.replace(/&/g, "&amp;").replace(/</g, "&lt;");
      document.body.appendChild(pre);
    }
  })();
</script>
</body>
</html>