我试图将用户输入的HTML格式的数据传递给本地驱动器上的csv文件。 但是似乎有些错误。
即使从其他来源复制的代码,我也尝试过下面的代码。
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\sample.txt";
var file = OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
</br></br></html>
未创建CSV文件,并且无法在HTML中获得任何错误。
答案 0 :(得分:2)
您没有使用变量fso调用OpenTextFile,还应记住IE有权在路径中写入
这应该对您有用:
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\Users\\yourUser\\sample.csv";
var file = fso.OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
您还可以使用适用于多种浏览器的此解决方案:
<html>
<head>
<script language="javascript">
function downloadCSV(form) {
const content = 'Write your csv content here!!';
const mimeType = 'text/csv;encoding:utf-8';
const fileName = 'download.csv';
const a = document.createElement('a');
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="downloadCSV(this.form)">
</form>
</body>
</html>