Downloading file though AJAX POST

后端 未结 3 1244
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 05:56

I\'m trying to provide a simple download using AJAX POST request. A user clicks a and the download begins (or a download dialog shows up, depending

相关标签:
3条回答
  • 2020-12-20 06:47

    I don't think its possible using ajax, I had the same issue and the download was not triggered. My solution was using only PHP:

    1. Create a new file when the page is loaded, on the background. This will be stored in a server location.

      $out = fopen('filename', 'w+');
      //write data in file
      fputcsv($out, some csv values );
      
    2. have a link to the client to download it

      <a href='<?php echo $filename;?>' >Export Data to CSV file</a>
      

    And depending on how often this is done, you must clean-up the downloads regularly to not fill the server.

    0 讨论(0)
  • 2020-12-20 06:51

    I do not get why you want to trigger an ajax call for download? Why don't you just do a regular <a href="download/me">Download</a> and set the mime type of that page. This way you can run any php code and then echo a mime type, this will not cause the page to reload and you will stay in the page from where you did the click.

    http://davidwalsh.name/php-header-mime

    0 讨论(0)
  • 2020-12-20 06:58

    You don't download the file using AJAX.

    You just have to give the URL like <a href="myFile.jpeg"> but the problem is that you have to force download using headers and URL Rewriting to intercept the requests:

    In case of an image:


    $filename = basename($_GET['img']); // don't accept other directories
    $size = @getimagesize($filename);
    $fp = @fopen($filename, "rb");
    if ($size && $fp)
    {
       header("Content-type: {$size['mime']}");
       header("Content-Length: " . filesize($filename));
       header("Content-Disposition: attachment; filename=$filename");
       header('Content-Transfer-Encoding: binary');
       header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
       fpassthru($fp);
       exit;
    }
    

    In this case.. the URL will not be changed (I think this is what you want)

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