我试图通过以下代码使用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;
}
}
}
}
但是当我尝试执行此代码时出现以下错误
无法构造'文件':第一个参数既不是数组,也不是 它是否有索引属性
请帮我解决这个问题
答案 0 :(得分:1)
如指示的错误消息,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
php://input
读取文件内容
$input = fopen("php://input", "rb");
请参阅Trying to Pass ToDataURL with over 524288 bytes Using Input Type Text