Download File Using Javascript/jQuery

前端 未结 28 2864
悲&欢浪女
悲&欢浪女 2020-11-21 05:11

I have a very similar requirement specified here.

I need to have the user\'s browser start a download manually when $(\'a#someID\').click();

But

28条回答
  •  隐瞒了意图╮
    2020-11-21 05:46

    I have had good results with using a FORM tag since it works everywhere and you don't have to create temporarily files on server. The method works like this.

    On the client side (page HTML) you create an invisible form like this

    Then you add this Javascript code to your button:

    $('#button').click(function() {
         $('#csv').val('---your data---');
         $('#downloadForm').submit();
    }
    

    The on the server-side you have the following PHP code in download.php:

    You can even create zip files of your data like this:

    open($file, ZipArchive::OVERWRITE);
    $zip->addFromString('test.csv', $_REQUEST['data']);
    $zip->close();
    
    header('Content-Type: application/zip');
    header('Content-Length: ' . filesize($file));
    header('Content-Disposition: attachment; filename="file.zip"');
    readfile($file);
    unlink($file); 
    

    The best part is it does not leave any residual files on your server since everything is created and destroyed on the fly!

提交回复
热议问题