2014-10-27 88 views
1

是否可以使用WordPress Ajax下载文件。我有这个功能来下载附件。在WordPress中使用ajax下载文件

function download_attachment() 
{ 
    $file_path = $_POST['filename']; 
    $file_mime = $_POST['mime']; 
    $data['file_path'] = file_exists($file_path); 

    try{ 
     header('Pragma: public'); // required 
     header('Expires: 0');  // no cache 
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
     header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_path)).' GMT'); 
     header('Cache-Control: private',false); 
     header('Content-Type: '.$file_mime); 
     header('Content-Disposition: attachment; filename="'.basename($file_path).'"'); 
     header('Content-Transfer-Encoding: binary'); 
     header('Content-Length: '.filesize($file_path)); // provide file size 
     header('Connection: close'); 
     set_time_limit(0); 
     @readfile("$file_path") or die("File not found."); 

    }catch(Exception $e) 
    { 
     $data['error'] = $e->getMessage() ." @ ". $e->getFile() .' - '. $e->getLine(); 
    } 
    } 
    echo json_encode($data); 
    die(); 
} 

它被钩到WordPress主要功能与此功能:

add_action('wp_ajax_download_attachment','download_attachment'); 

而jQuery代码是这样的:

var data = { 
     'function': 'download_attachment', 
     'filename': file_path, 
     'mime': mime 
    }; 

    jQuery.ajax({ 
     url: ajaxurl, 
     type: "POST", 
     data: data, 
     success: function(return_data, textStatus, jqXHR) { 
      parsedData = kalimahJS.parseJSON(return_data); 
      window.open(parsedData.url); 
     } 
    }) 

最终的结果是0显示在屏幕上。有没有另一种方法来做到这一点?

+0

尽量去除抑制在这里'@readfile (“$ file_path”)或死(“File not found。”);'也许文件未找到,但是你隐藏了错误。如果你这样做会怎样? – vaso123 2014-10-27 09:25:32

+0

我尝试过但没有任何反应。该文件确实存在,我已经放置了一个绝对路径并没有发生任何事情。 – 2014-10-27 09:32:49

+0

尝试2件事。第一,尝试'var_dump($ data);'它包含什么?因为看起来'json_encode'失败。第2位。你也可以尝试一下,如果你直接调用php,会发生什么。直接在ajax文件中设置'$ file_path'和'$ file_mime',然后调用该文件。如果没关系,那么数据是不正确的,你通过'$ _POST' – vaso123 2014-10-27 10:49:38

回答

0

尝试添加以下代码也

add_action('wp_ajax_nopriv_download_attachment', 'download_attachment'); 
+1

我加入并且我收到了相同的结果。 – 2014-10-27 09:44:19

+0

无法下载数据使用Ajax。 – huykon225 2017-12-12 02:31:11