New File stucks

2019-09-22 07:31发布

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.

1条回答
何必那么认真
2楼-- · 2019-09-22 08:26

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>

查看更多
登录 后发表回答