Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...