如何通过多个文件名进行PHP下载

时间:2018-08-10 12:20:12

标签: javascript php download

我正在尝试在PHP中实现下载功能。用户可以下载单个或多个文件。如果用户尝试下载单个文件,则文件将正常下载。如果用户尝试下载多个文件,则所有文件都将转换为zip并下载。

但是我的问题是如何传递文件名及其路径。对于单个文件,我使用

传递了它
window.location = directories_path + "?action=download&files="+download;

下载可以是我可以传递文件的数组。但是我无法通过他们。我的网址看起来很像

localhost/proj/Base?action=download&files=[object Object]

我什至尝试使用AJAX以json格式传递文件名。但这没用。

我的JS代码用于下载过程

$("input:checked").each(function(){
  if($(this).siblings('a').length > 0)
  {
    download.push({
      name: $(this).siblings('a').text(),
      path: $(this).siblings('a').attr('href'),
    });
  }
});
if( checked == 0 ) {
  alert("Please select any file to download");
} else {
  window.location = directories_path + "?action=download&files="+download;
}

我用于下载单个文件的php代码是

header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($file));
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($file);

我的问题是有什么办法可以让我在url中传递一个对象数组(文件名和文件路径),以便可以相应地下载文件。谢谢

1 个答案:

答案 0 :(得分:0)

感谢@ADyson,并感谢其他所有人。最后,这就是我的实现方式。我发布它是为了对某人有用。

我提出了AJAX发布请求,并返回了链接。最后,将window.location更改为多个文件的特定链接。但是对于单文件下载,有时可能无法执行。例如:如果将位置更改为PNG图像。浏览器将打开PNG图像,而不是下载它。因此,对于单个文件下载,我更喜欢使用HTML锚下载标签。

这是我的JQuery代码:

$(".uploaded_files").on('click', '#download', function(event){
download = [];
$("input:checked").each(function(){
  if($(this).siblings('a').length > 0)
  {
    download.push({
      name: $(this).siblings('a').text(),
      path: $(this).siblings('a').attr('href'),
    });
  }
});
if( checked == 0 ) {
  alert("Please select any file to download");
} else if( checked == 1) {
  $("body").append($('<a href="'+ download[0]['path']+'" download id="download_single"></a>'));
  console.log(download);
  document.getElementById('download_single').click();
  $("a#download_single").remove();
} else {
  alert("The download begins in few seconds");
  $.post('Base.php', {
    action: 'download',
    files: download //array of objects of files
  }, function(link) {
    window.location = link;
  });
}

});

这是我用于下载多个文件的PHP代码

$zip = new ZipArchive();
$zip_file = 'tmp/'.md5("download".rand(1,1000000)."zipfile").".zip";
if( $zip->open($zip_file,  ZipArchive::CREATE))
{
  foreach($files as $file)
  {
    $file['path'] = explode('uploads/', $file['path'])[1];
    $file['path'] = 'uploads/'.$file['path'];
    $zip->addFile($file['path'], $file['name'] );
  }
  $zip->close();
  header('Content-disposition: attachment; filename='.$zip_file.'');
  header('Content-type: application/zip');
  echo "http://localhost/".$zip_file;
  die();