2011-01-13 82 views
0

我有一个接受一堆数据的textarea。然后,我通过$ .ajax将其提交给处理该脚本并生成KML的PHP​​脚本。强制通过jQuery下载文件

var pData = $("textarea#data").serialize(); 
$.ajax(
{ 
    type: "POST", 
    url: "tools.php?mode=process", 
    data: pData, 
    success: function(data) 
    { 
     window.location.href = "tools.php?mode=download&"+pData; 
    }); 
}); 

这确实工作正常,直到我开始获得越来越多的数据。现在我得到一个URI太大的错误,并试图找到一个替代方法来强制文件下载。我也尝试使用$ .post(),但我无法强制它下载。

+1

你为什么要通过URL发送的所有数据到你的脚本,然后再? '进程'不能以某种方式保存数据? – 2011-01-13 17:43:56

回答

2

跟进的评论的讨论,这样做的最佳工作流程可能是

  1. 数据被通过Ajax和POST发送到mode=process;
  2. 脚本保存结果在一个临时文件(随机名称),并返回Ajax响应体
  3. location.href呼叫转到mode=download该文件和临时文件的名称
  4. 脚本打开临时文件名,使其通过并删除它
3

我发现将数据保存到一个文件,然后强制下载使用jQuery,创建文件,并与PHP保存数据的最佳方式:

 $data = ''; // data passed to a function or via $_POST['data'] 
     $targetFolder = $_SERVER['DOCUMENT_ROOT'] . '/location/of/file/'; 
     $savedFile = $targetFolder . md5($data). '.html'; 
     $handle = fopen($savedFile, 'w') or die('Cannot open file: '.$savedFile); 
     fwrite($handle, $data); 

     if(file_exists($savedFile)) { 
      $fileName = basename($savedFile); 
      $fileSize = filesize($savedFile); 

      // Output headers. 
      header("Cache-Control: private"); 
      header("Content-Type: application/stream"); 
      header("Content-Length: ".$fileSize); 
      header("Content-Disposition: attachment; filename=".$fileName); 

      // Output file. 
      readfile ($savedFile);     
      exit(); 
     } 
     else { 
      die('The provided file path: ' . $savedFile .' is not valid.'); 
     } 

上。点击功能使用jQuery或$。员额

var forceDownload_URL = 'your/download/function/url.php'; 

$('#download').click(function(){ 
    window.open(forceDownload_URL); 
}); 

// Post method untested, but writing on the fly when called as above works well 
// getting your forceDownload php to return the absolute path to your file 
$.post(forceDownload_URL,{postdata:my_data},function(data){ 
    window.open(data); 
});