Home > Web Front-end > JS Tutorial > How Can I Download a File Client-Side Using JavaScript Without Server Interaction?

How Can I Download a File Client-Side Using JavaScript Without Server Interaction?

Mary-Kate Olsen
Release: 2024-12-29 03:00:11
Original
124 people have browsed it

How Can I Download a File Client-Side Using JavaScript Without Server Interaction?

How to Download a File Without Server Interaction Using JavaScript

When creating a file that users can download, security concerns typically prevent direct writing to their machine. However, it is possible to create a file and prompt users to save it without involving the server.

HTML5 Solution

For browsers supporting HTML5, you can use the following code:

function download(filename, text) {
  // Create an anchor element pointing to the file's content
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  // Hide the anchor element
  element.style.display = 'none';

  // Append the element to the body to enable the download
  document.body.appendChild(element);

  // Simulate a click event to trigger the download
  element.click();

  // Remove the anchor element to prevent further interaction
  document.body.removeChild(element);
}
Copy after login

Usage

Use this function in your HTML code as follows:

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea name="text"></textarea>
  <input type="submit" value="Download">
</form>
Copy after login

When a user enters a file name and file content into the form and clicks the "Download" button, the file will be downloaded without interaction with the server.

The above is the detailed content of How Can I Download a File Client-Side Using JavaScript 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