Download textarea contents as a file using only Javascript (no server-side)

前端 未结 8 2269
挽巷
挽巷 2020-11-29 03:44

I am being asked to make a \"download\" button that downloads the contents of a textarea on the same page as a file, with the browser\'s \"Save As...\" dialog showing up. Co

相关标签:
8条回答
  • 2020-11-29 04:18

    Short answer: it's not posible. You have to POST it to server, and response from server can be "Content-disposition: attachment".

    0 讨论(0)
  • Based on @Cyrlop's answer and https://stackoverflow.com/a/41948732/3096687, this gives a way to specify a filename:

                function doDownload(str) {
                  function dataUrl(data) {
                    return "data:x-application/xml;charset=utf-8," + escape(data);
                  }
                  var downloadLink = document.createElement("a");
                  downloadLink.href = dataUrl(str);
                  downloadLink.download = "foo.xml";
    
                  document.body.appendChild(downloadLink);
                  downloadLink.click();
                  document.body.removeChild(downloadLink);
                }
    

    @Superphonic's solution is likely nicer if you don't mind including more bytes in your JavaScript.

    0 讨论(0)
提交回复
热议问题