How to read and write into file using JavaScript?

后端 未结 17 2503
孤街浪徒
孤街浪徒 2020-11-22 02:00

Can anybody give some sample code to read and write a file using JavaScript?

17条回答
  •  梦谈多话
    2020-11-22 02:27

    This Javascript function presents a complete "Save As" Dialog box to the user who runs this through the browser. The user presses OK and the file is saved.

    Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.

    // content is the data you'll write to file
    // filename is the filename
    // what I did is use iFrame as a buffer, fill it up with text function save_content_to_file(content, filename) { var dlg = false; with(document){ ir=createElement('iframe'); ir.id='ifr'; ir.location='about.blank'; ir.style.display='none'; body.appendChild(ir); with(getElementById('ifr').contentWindow.document){ open("text/plain", "replace"); charset = "utf-8"; write(content); close(); document.charset = "utf-8"; dlg = execCommand('SaveAs', false, filename+'.txt'); } body.removeChild(ir); } return dlg; }

    Invoke the function:

    save_content_to_file("Hello", "C:\\test");
    

提交回复
热议问题