【问题标题】:Javascript read file without using inputJavascript在不使用输入的情况下读取文件
【发布时间】:2014-02-02 14:26:39
【问题描述】:

我有这个代码,对于要转换为 base64 的文件,我必须单击选择文件,然后选择它。我想对文件名进行硬编码,以便在页面加载时将其转换为 base64。

JavaScript:

var handleFileSelect = function(evt) {
  var files = evt.target.files;
  var file = files[0];

  if (files && file) {
    var reader = new FileReader();

    reader.onload = function(readerEvt) {
      var binaryString = readerEvt.target.result;
      document.getElementById("base64textarea").value = btoa(binaryString);
    };

    reader.readAsBinaryString(file);
  }

  if (window.File && window.FileReader
      && window.FileList && window.Blob) {
    document.getElementById('filePicker')
        .addEventListener('change', handleFileSelect, false);
  } else {
    alert('The File APIs are not fully supported in this browser.');
  }
};

HTML:

<div>
  <div>
    <label for="filePicker">Choose or drag a file:</label><br/>
    <input type="file" id="filePicker">
  </div>
  </br>
  <div>
    <h1>Base64 encoded version</h1>
    <textarea id="base64textarea"
        placeholder="Base64 will appear here"
        cols="50" rows="15">
    </textarea>
  </div>
</div>

编辑:谢谢你的回答,他们真的很有帮助。

【问题讨论】:

  • 我感觉浏览器不会允许你随意从用户的文件系统中加载文件。某些事件只能从用户直接输入中生成。
  • 看起来您甚至无法从 javascript 中设置 &lt;input type="file"&gt; 元素的值。见Notes: File Inputs

标签: javascript file input onload


【解决方案1】:

你根本无法做你想做的事。作为安全措施,无法通过 Javascript 设置输入元素的路径。请在此处查看:How to resolve the C:\fakepath?

【讨论】:

    【解决方案2】:

    您可以启动 chromium,设置了 --allow-file-access-from-files 标志的 chrome 浏览器,使用 fetch()XMLHttpRequest() 从本地文件系统请求文件。

    fetch("file:///path/to/file")
    .then(response => response.arrayBuffer())
    .then(ab => {
      // do stuff with `ArrayBuffer` representation of file
    })
    .catch(err => console.log(err));
    

    另见Read local XML with JS

    【讨论】:

      【解决方案3】:

      File API 不适合在没有用户干预的情况下读取本地文件,但 Web API(当然,在其限制范围内,例如在未明确启用对本地文件的访问等情况下无法在 Chromium 中工作)。

      所以,在这里,如果其他人需要一个工作示例来说明如何在没有用户干预的情况下加载本地文件,ie,而不需要用户按下任何 INPUT 按钮(但仍然给出用户一种中止加载的方法)。

      参数:文件名、请求类型(文本、blob 等)、MIME 类型和文件完全加载后要执行的函数。文件加载到变量 X 中,然后用于填充对象。

      要中止文件读取,只需单击进度条(也只是一个示例,对程序运行而言不是必需的)。因为它是异步的,所以可以同时读取尽可能多的文件(为每个文件创建一个进度条)。

      我只为文本文件和视频创建了示例,但它应该适用于任何类型的文件。

      <html>
      <head>
      <meta charset="utf-8"/>
      <script type="text/javascript">
      function LoadFile(FileName,RespType,FileType,RunMe)
      {   var AJAXFileReader=new XMLHttpRequest();
      
          // Creates new progress bar.
          var ProgressBar=CreateSVGProgBar("ProgressBars");
      
          AJAXFileReader.addEventListener("progress",
              function FRProgress(AJAXFREvt)
              {   // Calculate progress.
                  var X=-1;
      
                  if (AJAXFREvt.lengthComputable)
                      X=Math.trunc(AJAXFREvt.loaded/AJAXFREvt.total*100);
      
                  ShowProgressBar(ProgressBar,FileName,X);
              });
      
          AJAXFileReader.addEventListener("error",function FRFailed()
              {   // This will be executed if an error occurs.
                  console.log("Error:",this.status);
              });
      
          AJAXFileReader.addEventListener("timeout",function FRTimeOut()
              {   // This will be executed if the reading times out.
                  console.log("File reading timed out!");
              });
      
          AJAXFileReader.addEventListener("abort",
              function FRCancel()
              {   // This will confirm reading was aborted.
                  console.log("File reading cancelled by user!");
              });
      
          ProgressBar.addEventListener("click",
              function KillMe()
              {   // Adds an abort command to the object.
                  console.log(AJAXFileReader.readyState);
                  if (AJAXFileReader.readyState!=4)
                  {   console.log("Aborting file reading...");
                      AJAXFileReader.abort();
                  }
                  ProgressBar.removeEventListener("click",KillMe);
              },
              false);
      
          AJAXFileReader.addEventListener("load",
              function Finished()
              {   // When reading is finished, send data to external function.
                  if ((this.readyState==4)&&(this.status==200))
                  {   ShowProgressBar(ProgressBar,FileName,100);
                      RunMe(this.response);
                      //ProgressBar.click();
                  }
              },
              false);
      
          AJAXFileReader.open("GET",FileName,true);
          AJAXFileReader.overrideMimeType(FileType);
          AJAXFileReader.responseType=RespType;
          AJAXFileReader.timeout=10000; // Setting time-out to 10 s.
      
          AJAXFileReader.send();
      }
      
      function CreateSVGProgBar(AnchorId)
      {   // Creates new SVG progress bar.
          var Parent=document.getElementById(AnchorId);
          var NewSVG=document.createElementNS("http://www.w3.org/2000/svg","svg");
          NewSVG.setAttribute("viewBox","0 0 102 22");
          NewSVG.setAttribute("width","102");
          NewSVG.setAttribute("height","22");
          Parent.appendChild(NewSVG);
          return NewSVG;
      }
      
      function ShowProgressBar(E,N,X)
      {   // Show progress bar.
          var P=X<0?"???":X+"%";
      
          E.innerHTML="<text x=\"50\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+N+"</text><rect x=\"1\" y=\"1\" width=\""+X+"\" height=\"20\" fill=\""+(X<100?"#FF0000":"#0000FF")+"\" stroke=\"none\"/><rect x=\"1\" y=\"1\" width=\"100\" height=\"20\" fill=\"none\" stroke=\"black\" stroke-width=\"1\"/><text x=\""+X/2+"\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+P+"</text>";
      }
      
      function TracerOn(X)
      {   // This will be executed after the file is completely loaded.
          document.getElementById("Tron").innerHTML=X;
      }
      
      function PlayIt(X)
      {   // This will be executed after the file is completely loaded.
          var blob_uri=URL.createObjectURL(X);
          document.getElementById("MagicalBox").appendChild(document.createElement("source")).src=blob_uri;
      }
      
      function Startup()
      {   // Run after the Page is loaded.
          LoadFile("example.txt","text","text/plain;charset=utf-8",TracerOn);
          LoadFile("video.mp4","blob","video/mp4",PlayIt);
      }
      
      </script>
      </head>
      
      <body onload="Startup()">
      
      <div id="ProgressBars"></div>
      
      <div id="Tron">Text...</div>
      
      <video id="MagicalBox" width="400" controls>Video...</video>
      
      </body>
      </html>
      

      【讨论】:

      • 我可以使用这个脚本来显示本地图像吗?
      猜你喜欢
      • 2014-04-29
      • 1970-01-01
      • 2019-10-02
      • 2014-12-26
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多