Download file through an ajax call php

后端 未结 5 1274
别跟我提以往
别跟我提以往 2020-11-22 14:51

I have a button and onclick it will call an ajax function.

Here is my ajax function

function csv(){

    ajaxRequest = ajax();//ajax()          


        
相关标签:
5条回答
  • 2020-11-22 14:53

    AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

    0 讨论(0)
  • 2020-11-22 14:56

    I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.

    Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.

    Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:

    $('iframe_dl').src="/app?download=1&filename=" + the_filename
    

    Server slurps the file, unlinks it, and sends the stream to the client, with these headers:

    Content-Type:'application/force-download'
    Content-Disposition:'attachment; filename=the_filename'
    

    Works like a charm.

    0 讨论(0)
  • 2020-11-22 15:01

    You can't download the file directly via ajax.

    You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe and set the URL of the source of that iframe dynamically. This way you can download the file without refreshing the page.

    Here is the code

    $.ajax({
        url : "yourURL.php",
        type : "GET",
        success : function(data) {
            $("#iframeID").attr('src', 'downloadFileURL');
        }
    });
    
    0 讨论(0)
  • 2020-11-22 15:06

    @joe : Many thanks, this was a good heads up!

    I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

    So that's how I did it (using JQuery to handle the AJAX request):

    1. Initial post request:

      var parameters = {
           pid     : "mypid",
         "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
      }

      var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

    The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

     //Code to create the zip file
     //......
     //Id of the file
     $zipid = "myzipfile.zip"
     //Download Link - it can be prettier
     $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
     //JSON response to be handled on the client side
     $result = '{"success":1,"path":"'.$dlink.'","error":null}';
     header('Content-type: application/json;');
     echo $result;
    

    The "request/download" can perform some security checks, if needed, and generate the file transfer:

    $fn = $_GET['file'];
    if ($fn) {
      //Perform security checks
      //.....check user session/role/whatever
      $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
      if (file_exists($result)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename='.basename($result));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($result));
        ob_clean();
        flush();
        readfile($result);
        @unlink($result);
      }
    
    }
    
    0 讨论(0)
  • 2020-11-22 15:17

    A very simple solution using jQuery:

    on the client side:

    $('.act_download_statement').click(function(e){
        e.preventDefault();
        form = $('#my_form');
        form.submit();
    });
    

    and on the server side, make sure you send back the correct Content-Type header, so the browser will know its an attachment and the download will begin.

    0 讨论(0)
提交回复
热议问题