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.
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); }
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>
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!