Javascript 如何读取本地文本文件?
我试图通过创建一个函数来编写一个简单的文本文件读取器,该函数接收文件的路径并将每行文本转换为一个字符数组,但它不起作用Javascript 如何读取本地文本文件?,javascript,file-io,xmlhttprequest,Javascript,File Io,Xmlhttprequest,我试图通过创建一个函数来编写一个简单的文本文件读取器,该函数接收文件的路径并将每行文本转换为一个字符数组,但它不起作用 function readTextFile() { var rawFile = new XMLHttpRequest(); rawFile.open("GET", "testing.txt", true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4) {
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "testing.txt", true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
var allText = rawFile.responseText;
document.getElementById("textSection").innerHTML = allText;
}
}
rawFile.send();
}
这里出了什么问题
在从a修改了一点代码之后,这似乎仍然不起作用,现在它给了我一个XMLHttpRequest
exception 101
我已经在Firefox上测试过了,它可以工作,但在Google Chrome上它就是不工作,它一直给我一个异常101。我如何才能让它不仅在Firefox上工作,而且在其他浏览器(尤其是Chrome)上工作?您需要检查状态0(就像使用
XMLHttpRequest
本地加载文件时,您不会得到返回的状态,因为它不是来自Webserver
)
并在文件名中指定file://
:
readTextFile("file:///C:/your/path/to/file.txt");
尝试创建两个函数:
function getData(){ //this will read file and send information to other function
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var lines = xmlhttp.responseText; //*here we get all lines from text file*
intoArray(lines); *//here we call function with parameter "lines*"
}
}
xmlhttp.open("GET", "motsim1.txt", true);
xmlhttp.send();
}
function intoArray (lines) {
// splitting all text data into array "\n" is splitting data from each new line
//and saving each new line as each element*
var lineArr = lines.split('\n');
//just to check if it works output lineArr[index] as below
document.write(lineArr[2]);
document.write(lineArr[3]);
}
如果您已经尝试过,请按如下方式键入“false”:
rawFile.open("GET", file, false);
<input type="file" onchange="this.files[0].text().then(t => console.log(t))">
其他示例-使用FileReader类的my reader
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
<a href="#" id="viewSource">Source file</a>
</body>
</html>
函数PreviewText(){
var of reader=new FileReader();
readAsDataURL(document.getElementById(“uploadText”).files[0]);
oFReader.onload=函数(OFRENT){
document.getElementById(“uploadTextValue”).value=ofretent.target.result;
document.getElementById(“obj”).data=ofretent.target.result;
};
};
jQuery(文档).ready(函数(){
$('#viewSource')。单击(函数()
{
var text=$('#uploadTextValue').val();
警报(文本);
//这里是阿贾克斯
});
});
访问!然后转到readAsText一节并尝试该示例。您将能够了解FileReader的readAsText函数是如何工作的
var openFile=函数(事件){
var输入=event.target;
var reader=new FileReader();
reader.onload=函数(){
var text=reader.result;
var节点=document.getElementById('output');
node.innerText=文本;
console.log(reader.result.substring(0200));
};
reader.readAsText(input.files[0]);
};
...
Jon Perryman
是的,JS可以读取本地文件(请参见FileReader()),但不能自动读取:用户必须使用html
将文件或文件列表传递给脚本
然后使用JS可以处理(示例视图)文件或文件列表、文件的某些属性以及文件内容
出于安全原因,JS无法自动(无需用户输入)访问其计算机的文件系统
要允许JS自动访问本地fs,需要创建一个hta文档,而不是包含JS的html文件
hta文件中可以包含JS或VBS
但是hta可执行文件只能在windows系统上工作
这是标准的浏览器行为
谷歌Chrome也在fs API上工作,更多信息请点击此处:这可能会有所帮助
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "sample.txt", true);
xmlhttp.send();
var input=document.getElementById(“myFile”);
var output=document.getElementById(“输出”);
input.addEventListener(“更改”,函数(){
if(this.files&&this.files[0]){
var myFile=this.files[0];
var reader=new FileReader();
reader.addEventListener('load',函数(e){
output.textContent=e.target.result;
});
reader.readAsBinaryString(myFile);
}
});代码>
在javascript中引入后,读取文件内容再简单不过了
读取文本文件
fetch('file.txt')
.then(response => response.text())
.then(text => console.log(text))
// outputs the content of the text file
fetch('file.json')
.then(response => response.json())
.then(jsonResponse => console.log(jsonResponse))
// outputs a javascript object from the parsed json
var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
读取json文件
fetch('file.txt')
.then(response => response.text())
.then(text => console.log(text))
// outputs the content of the text file
fetch('file.json')
.then(response => response.json())
.then(jsonResponse => console.log(jsonResponse))
// outputs a javascript object from the parsed json
var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
更新日期:2018年7月30日(免责声明):
这项技术在Firefox中运行良好,但在编写此更新时,Chrome的fetch
实现似乎不支持文件://
URL方案(在Chrome 68中测试)
更新-2(免责声明):
基于与Chrome相同的(安全)原因,CORS请求非HTTP
,该技术不适用于高于68版(2019年7月9日)的Firefox。看
$(文档).ready(函数(){
$.ajax({`在此处输入代码`
url:“TextFile.txt”,
数据类型:“文本”,
成功:函数(数据){
var text=$('#newCheckText').val();
var-str=数据;
var str_array=str.split('\n');
对于(var i=0;i ');
}
}
});
$(“#ckbCheckAll”)。单击(函数(){
$(“.checkBoxClass”).prop('checked',$(this.prop('checked'));
});
});
选择全部
由于同源策略,不支持Chrome中的本地AJAX调用。
chrome上的错误消息如下:
协议方案不支持跨源请求:http、数据、chrome、chrome扩展、https
这意味着chrome为每个域创建了一个虚拟磁盘,以使用http/https协议保存域提供的文件。对该virt之外的文件的任何访问
function readTextFile(filePath){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", filePath , true);
rawFile.send(null);
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4){
if(rawFile.status === 200 || rawFile.status == 0){
var allText = rawFile.responseText;
console.log(allText);
}
}
}
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var allText = xmlhttp.responseText;
}
};
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
const logFileText = async file => {
const response = await fetch(file)
const text = await response.text()
console.log(text)
}
logFileText('file.txt')
function readTextFile(file) {
var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
rawFile.open("GET", file, false); // open with method GET the file with the link file , false (synchronous)
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
{
if(rawFile.status === 200) // status 200: "OK"
{
var allText = rawFile.responseText; // Returns the response data as a string
console.log(allText); // display text on the console
}
}
}
rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}
readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path
function loadMyFile(){
console.log("ut:"+unixTimeSec());
loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
var mA_=mSdata.split("\n");
console.log(mA_.length);
}
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
return f.toString().
replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
return Math.round( (new Date()).getTime()/1000);
}
var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});
async function loadText(url) {
text = await fetch(url);
//awaits for text.text() prop
//and then sends it to readText()
readText(await text.text());
}
function readText(text){
//here you can continue with your JS normal logic
console.log(text);
}
loadText('test.txt');
<input type="file" onchange="this.files[0].text().then(t => console.log(t))">
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await file.text();
console.log(text);
}
</script>
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await (new Response(file)).text();
console.log(text);
}
</script>
var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
// read the contents of a file input
const readInputFile = (inputElement, callback) => {
const reader = new FileReader();
reader.onload = () => {
callback(reader.result)
};
reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
export const openFile = (callback) => {
var el = document.createElement('input');
el.setAttribute('type', 'file');
el.style.display = 'none';
document.body.appendChild(el);
el.onchange = () => {readInputFile(el, (data) => {
callback(data)
document.body.removeChild(el);
})}
el.click();
}
// prompt the user to select a file and read it
openFile(data => {
console.log(data)
})