Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

javascript - New File stucks

I am new in javascript and was trying to read and write in local txt file so I did as I found in the web but for some reason it stucks in new File instantiation:

<script type="text/javascript">
var txtFile = "d:/test.txt"
alert('point 1');
var file = new File(txtFile);
alert('point 2');
</script>

It prints only 'point 1' string. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

new File() constructor requires at least two parameters; first parameter an array containing String, ArrayBufferView, ArrayBuffer Blob or another File object; the second the file name. You cannot specify a download directory for files using javascript, but you can set a download directory at browser settings or preferences. You can also utilize download attribute at a element to set file name at Save File dialog.

I am new in javascript and was trying to read and write in local txt file

You could use <input type="file"> element to retrieve test.txt, and edit .txt file at <textarea> before re-saving with same file name. See also Edit, save, self-modifying HTML document; format generated HTML, JavaScript , How to Write in file (user directory) using JavaScript?

<script type="text/javascript">
  var txtFile = "test.txt";
  var text = "abc";
  var file = new File([text], txtFile);
  console.log(file);
  var a = document.createElement("a");
  a.download = file.name;
  a.href = URL.createObjectURL(file);
  document.body.appendChild(a);
  a.innerHTML = file.name;
  a.onclick = function() {
    this.parentElement.removeChild(this)
  }
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...