Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Требуется сохранить содержимое блока в файл и скачать (https://javascript.ru/forum/misc/66821-trebuetsya-sokhranit-soderzhimoe-bloka-v-fajjl-i-skachat.html)

sergey24 12.01.2017 17:54

Требуется сохранить содержимое блока в файл и скачать
 
Добрый день уважаемые форумчане. Перейду сразу к делу.
Есть блок:
<div class="block">123</div>
И кнопка <button class="save">Сохранить</button>
Как сделать так, чтобы после нажатия на кнопку скачивался txt файл с содержимым блока block, в данном случае должен скачаться файл со следующим текстом внутри "123".

sergey24 12.01.2017 20:38

Нашёл решение, но оно работает с textarea только. Как сделать, чтобы данные брались из дива?
Index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />

        <title>Generating files with JS & PHP | Tutorialzine Demo</title>

        <!-- Our CSS stylesheet file -->
        <link rel="stylesheet" href="assets/css/styles.css" />

        <!--[if lt IE 9]>
          <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <header>
            <h1>Generating Files with JavaScript</h1>
            <h2><a href="http://tutorialzine.com/2011/05/generating-files-javascript-php/">« Read and download on Tutorialzine</a></h2>
        </header>

        <form action="./" method="post">
            <textarea></textarea>
            <a href="#" class="blueButton" id="download">Download</a>
        </form>

        <footer>Another cool example: <a href="#" id="downloadPage">download this page.</a> <b>To download the source code, visit <a href="http://tutorialzine.com/2011/05/generating-files-javascript-php/">Tutorialzine.com</a></b></footer>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
        <script src="assets/js/jquery.generateFile.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>

download.php
if(empty($_POST['filename']) || empty($_POST['content'])){
    exit;
}

$filename = preg_replace('/[^a-z0-9\-\_\.]/i','',$_POST['filename']);

header("Cache-Control: ");
header("Content-type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');

echo $_POST['content'];

assets/jquery.generateFile.js
(function($){

    $.generateFile = function(options){

        options = options || {};

        if(!options.script || !options.filename || !options.content){
            throw new Error("Please enter all the required config options!");
        }

        var iframe = $('<iframe>',{
            width:1,
            height:1,
            frameborder:0,
            css:{
                display:'none'
            }
        }).appendTo('body');

        var formHTML = '<form action="" method="post">'+
            '<input type="hidden" name="filename" />'+
            '<input type="hidden" name="content" />'+
            '</form>';

        setTimeout(function(){


            var body = (iframe.prop('contentDocument') !== undefined) ?
                            iframe.prop('contentDocument').body :
                            iframe.prop('document').body;   
            body = $(body);

            body.html(formHTML);

            var form = body.find('form');

            form.attr('action',options.script);
            form.find('input[name=filename]').val(options.filename);
            form.find('input[name=content]').val(options.content);

            form.submit();
        },50);
    };

})(jQuery);

assets/script.js
$(document).ready(function(){

    $('#download').click(function(e){

        $.generateFile({
            filename    : 'export.txt',
            content     : $('textarea').val(),
            script      : 'download.php'
        });

        e.preventDefault();
    });

    $('#downloadPage').click(function(e){

        $.generateFile({
            filename    : 'page.html',
            content     : $('html').html(),
            script      : 'download.php'
        });

        e.preventDefault();
    });

});

fuckingquest 12.01.2017 20:57

<div id = "content">123</div>
<button id = "b">сoхранить</button>

<script>

a = document.createElement("a")
a.setAttribute("href", "data:text/plain," + content.innerHTML)
a.setAttribute("download", "filename.txt")

b.onclick = function(){ a.click() }





</script>

sergey24 12.01.2017 21:00

Спасибо большое:)

laimas 13.01.2017 07:49

Цитата:

Сообщение от sergey24
Generating files with JS & PHP

А использовать нормальный редактор?

andyyy 13.01.2017 13:22

А не легче просто <a href='ваш файл'>123</a>))


Часовой пояс GMT +3, время: 22:17.