Core JavaScript

Write to a File

This example program demonstrates how to write a file in JavaScript. To write the file, first press the button to generate the data for the file. Then click the link to write the file to your hard drive.

WriteFile.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript</title>
</head>
<body>
  <button onclick="CreateFile('TestSvgFile.svg', 'text/plain')">Click to create the file</button>
  <a href="" id="idA">Click this link to write the created file.</a>
  <script type="text/javascript" src="WriteFile.js"></script>
</body>
</html>

WriteFile.js

function CreateFile(sFileName, sDataType) {
  var sFileContents = '<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">'+
    '<rect width=\"150\" height=\"150\" fill=\"rgb(255, 225, 200)\"'+
      ' stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\">'+
    '</rect>'+
  '</svg>';
  var qAnchor = document.getElementById("idA");
  var qContents = new Blob([sFileContents], {type: sDataType});
  qAnchor.href = URL.createObjectURL(qContents);
  qAnchor.download = sFileName;
}
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.