Can I write files with HTML5/JS?

后端 未结 6 955
时光说笑
时光说笑 2020-11-30 05:13

I wonder if there is any way I can write to files from HTML5/JS? In the broswer ...

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 05:33

    Assuming your end goal is to let the user save your file somewhere where they will find it, as when right-clicking a link and choosing "Save As...", there isn't wide browser coverage for those APIs yet, likely due to security considerations.

    What you can do, however – APIs or not – is cheesing it with a link to a data: uri with a download attribute specifying your suggested filename. For instance:

    Save
    

    When clicked, at least in Chrome, this will save a file containing the text mostly harmless (and a trailing newline) as earth.txt in your download directory. To set the file contents from javascript instead, call this function first:

    function setSaveFile(contents, file_name, mime_type) {
      var a = document.getElementById('save');
      mime_type = mime_type || 'application/octet-stream'; // text/html, image/png, et c
      if (file_name) a.setAttribute('download', file_name);
      a.href = 'data:'+ mime_type +';base64,'+ btoa(contents || '');
    }
    

提交回复
热议问题