我正在尝试通过以下代码使用 JavaScript 将一些字符串写入文件
var txtfile ="../wp-content/plugins/MedicAdvisor/test.txt";
var file = new File("hello",txtfile);
//file = fopen("", 3);// opens the file for writing
file.open("w");
var currentrow = 0;
var nextrow = 0;
var type = " ";
var noofrows = 0;
var noofcells = 0;
var contentarray;
var row = document.getElementsByTagName('tr');
//get all elements having input tag
var inp = document.getElementsByTagName('input');
// traverse through all input tags
for (var i=2; i<inp.length; i++){
// see if it is a heckbox
if(inp[i].type == "checkbox"){
// see if it is checked
if(inp[i].checked == true){
//index of current row
currentrow = inp[i].parentNode.parentNode.rowIndex;
//event type
type = inp[i].parentNode.parentNode.cells[6].innerHTML.trim();
if (type == "cycling_road_race"){
noofrows = 6;
for(var j=0; j<noofrows; j++){
noofcells = row[currentrow + j + 1].cells.length;
for (var k=1; k<noofcells; k++){
//alert (row[currentrow + j + 1].cells[k].innerHTML.replace('<br>' , ' '));
contentarray.push(row[currentrow + j + 1].cells[k].innerHTML.replace('<br>' , ' '));
file.writeln(row[currentrow + j + 1].cells[k].innerHTML.replace('<br>' , ' '));
}
}
}
else if (type == "cycling_criterium_or_circuit_race"){
noofrows = 6;
}else if (type == "cycling_cyclocross"){
noofrows = 6;
}else if (type == "running_race"){
noofrows = 6;
}else if (type == "rugby_football_hockey"){
noofrows = 6;
}else if (type == "music_festival"){
noofrows = 6;
}else if (type == "manual_selection"){
noofrows = 5;
}
}
}
}
但是当我尝试执行此代码时出现以下错误
Failed to construct 'File': The 1st argument is neither an array, nor does it have indexed properties
请帮我解决这个问题
最佳答案
如错误消息所示,File
构造函数需要一个数组作为第一个参数。另外,第二个参数应该只是文件名和扩展名。您还可以将 type
设置为有效的 MIME
类型,并将 lastModified
设置为 File
构造函数的第三个参数处的对象属性.
var txtfile = "test.txt";
var file = new File(["hello"], txtfile
, {type:"text/plain", lastModified: new Date().getTime()});
File.prototype
没有 .open
方法。您可以使用 File.prototype.slice()
创建一个新的 File
对象,并将新数据连接到之前创建的 File
对象。
file = new File([file.slice(0, file.length), /* add content here */], file.name);
将File
对象保存到服务器需要将File
对象发布到服务器以读取文件数据的内容。
var request = new XMLHttpRequest();
request.open("POST", "/path/to/server");
request.send(file);
可以使用 php://input
在 php
读取文件内容
$input = fopen("php://input", "rb");
参见Trying to Pass ToDataURL with over 524288 bytes Using Input Type Text
关于JavaScript - New File() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41116513/