我有此代码,要将文件转换为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, usefetch()
ofXMLHttpRequest()
to request file from local filesystem.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中,然后用于填充对象。
要中止文件读取,只需单击进度条(也只是一个示例,对于程序正常工作不是必需的)。因为它是异步的,所以可以同时读取所需数量的文件(为每个文件创建一个进度条)。
我只为文本文件和视频创建了示例,但它可以与任何类型的文件一起使用。