是否可以使用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。还有其他方法可以做到这一点吗?
最佳答案
由于没有人回答过这个问题,特别是针对 WordPress,我想我会分享我的答案:
比如说,我想提供一个日志文件,以便于我的插件的用户下载(这就是我现在正在做的事情)。我要做的如下:
注册 AJAX 操作
add_action('wp_ajax_daan_download_log', 'daan_download_log');
创建函数
function daan_download_log()
{
check_ajax_referer('daan-nonce-value, 'nonce');
if (!current_user_can('manage_options')) {
wp_die(__("Hmmm, you're not supposed to be here.", 'my-plugin-name));
}
$filename = '/path/to/filename.log';
if (!file_exists($filename)) {
wp_die();
}
$basename = basename($filename);
$filesize = filesize($filename);
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
header("Content-Disposition: attachment; filename=$basename");
header("Content-Length: $filesize");
header('Pragma: public');
flush();
readfile($filename);
wp_die();
}
指向 AJAX 操作的链接
您可以在任何需要下载文件的地方添加此内容。
<?php $nonce = wp_create_nonce('daan-nonce-value'); ?>
<a href='<?php echo admin_url("admin-ajax.php?action=daan_download_log&nonce=$nonce"); ?>' class="button button-primary">Download Log File</a>
关于jquery - 在 WordPress 中使用 ajax 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26584349/