How can I create a file in memory for the user to download instead of going through the server?
P粉231112437
P粉231112437 2023-08-23 17:55:41
0
2
463
<p>Is there a way to create a text file on the client side and prompt the user to download it without any interaction with the server? </p> <p>I know I can't write directly to their computer (security, etc.), but can I create the file and prompt them to save? </p>
P粉231112437
P粉231112437

reply all(2)
P粉473363527

Simple solution for HTML5 browsers...

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);
}
form * {
  display: block;
  margin: 10px;
}
<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>

use

download('test.txt', 'Hello world!');
P粉727531237

You can use data URI. Browser support varies; see Wikipedia. Example:

<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

Octet stream is used to force download prompts. Otherwise, it may open in the browser.

For CSV you can use:

<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>

TryjsFiddle Demo.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!