Home > Web Front-end > JS Tutorial > How Can I Create and Download Text Files Client-Side Without Server Interaction?

How Can I Create and Download Text Files Client-Side Without Server Interaction?

Mary-Kate Olsen
Release: 2024-12-21 13:27:16
Original
426 people have browsed it

How Can I Create and Download Text Files Client-Side Without Server Interaction?

Creating Files in User Memory for Download

Generating text files on the client side and prompting users to download them without server involvement is possible. This approach circumvents direct file writing to the user's computer due to security constraints.

Solution for HTML5 Browsers

For HTML5-compliant browsers, the following JavaScript code enables you to create and prompt the user to save a file:

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}
Copy after login

To use this code, provide the desired file name and text content as arguments to the download() function. A link element is created with the data URL and download attribute set. The element is then made invisible, added to the document body, clicked to initiate the download, and finally removed.

This method provides a simple solution for generating and prompting users to save text files on the client side without server interaction.

The above is the detailed content of How Can I Create and Download Text Files Client-Side Without Server Interaction?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template