Javascript读取文件而不使用输入

我有此代码,要将文件转换为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>

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

评论
所以狠在乎
所以狠在乎

You can launch chromium, chrome browser with --allow-file-access-from-files flag set, use fetch() of XMLHttpRequest() to request file from local filesystem.

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

See also Read local XML with JS

点赞
评论
云淡,风清
云淡,风清

You simply can't do what you are trying to do. Setting the path for an input element through Javascript is not possible, as a security measure. Please check here: How to resolve the C:\fakepath?

点赞
评论
院子里画沙
院子里画沙

File API不能在没有用户干预的情况下读取本地文件,但是Web API可以(当然,在其局限性之内,例如在不显式启用对本地文件的访问权限的情况下不能在Chromium中工作)。

因此,在这种情况下,如果有人需要一个有效的示例,说明如何在无需用户干预的情况下加载本地文件,即无需用户按下任何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>
点赞
评论