Home > Web Front-end > JS Tutorial > How Can JavaScript Write Data to a File for Download?

How Can JavaScript Write Data to a File for Download?

DDD
Release: 2024-12-26 03:22:09
Original
969 people have browsed it

How Can JavaScript Write Data to a File for Download?

Writing Data to File in JavaScript

While JavaScript does not natively support file writing, it can still be achieved through the clever use of Blobs and URL.createObjectURL.

Browsers allow the creation of files using these methods. However, due to security concerns, direct saving of created files is prohibited. Instead, a download link can be provided to the user. Browsers may support the "download" attribute, which allows you to suggest a file name.

The code below provides a function to generate a text file from given text:

var makeTextFile = function (text) {
  var data = new Blob([text], {type: 'text/plain'});
  return window.URL.createObjectURL(data);
};
Copy after login

To initiate a download from a textarea, you can use the following code:

var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

create.addEventListener('click', function () {
  var link = document.createElement('a');
  link.setAttribute('download', 'info.txt');
  link.href = makeTextFile(textbox.value);
  document.body.appendChild(link);

  // simulate mouse click on link to start download
  var event = new MouseEvent('click');
  link.dispatchEvent(event);
  document.body.removeChild(link);
});
Copy after login

The above is the detailed content of How Can JavaScript Write Data to a File for Download?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template