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
457

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?

I know I can't write directly to their computer (security, etc.), but can I create the file and prompt them to save?

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; }

use

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

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

    text file

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

    For CSV you can use:

    CSV Octet

    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!