javascript - Send files to the client with jquery ajax and php -
i trying send files client via jquery, ajax, , php. using jquery v1.11.2 , xampp v3.2.1,
here jquery code:
<script> $(document).ready(function(){ $("#mybtn").click(function(){ $.ajax({ // post file name type: "post", data: { file: "testfile.xlsx" }, url: "sendfile.php", context: $("#result"), success: function(data, status, xhr){ $(this).html(data); } }); }); }); </script>
sendfile.php:
<?php function send_file($name) { // function ... send file client ob_end_clean(); $path = $name; //cek connection if lost connection client if (!is_file($path) or connection_status()!=0) return(false); //header //------------------------------------------------------------- header("cache-control: no-store, no-cache, must-revalidate"); header("cache-control: post-check=0, pre-check=0", false); header("pragma: no-cache"); header("expires: ".gmdate("d, d m y h:i:s", mktime(date("h")+2, date("i"), date("s"), date("m"), date("d"), date("y")))." gmt"); //set last modified property header("last-modified: ".gmdate("d, d m y h:i:s")." gmt"); header("content-type: application/octet-stream"); header("content-length: ".(string)(filesize($path))); header("content-disposition: inline; filename=$name"); // file header("content-transfer-encoding: binary\n"); //----------------------------------------------------------------- if ($file = fopen($path, 'rb')) { // send file while(!feof($file) , (connection_status()==0)) { print(fread($file, 1024*8)); flush(); } fclose($file); } return((connection_status()==0) , !connection_aborted()); } // send file if(!send_file($_post['file'])){ echo "error."; }
when press button no files received instead of random sentences in #result
if use directly in php functions working properly
send_file("testfile.xlsx");
are there more effective methods?
if you're looking method similar that, try using 'uploadify' free , easy --> http://www.uploadify.com/demos/
Comments
Post a Comment