重新载荷zip文件再次不重写zip文件-Ziparchive php



因此,我创建了一些使用ziparchive创建zip文件的PHP代码。这将创建一个zip文件并下载。要启动下载,我将链接放在iframe中包含下面的PHP代码的PHP文件的链接中。然后将此iframe插入到HTML文档中。

因此,每当HTML文档加载时,下载器都会启动。我在iframe标签中创建了Onload属性,该属性将调用一个函数以显示重新负载按钮。

因此,如果用户单击" redownload"按钮,我希望它再次下载同一zip文件,但不要再次重新创建zip文件过程。我该怎么做?

谢谢!

我的html代码:

<iframe src="phpfile.php" onload="myFrameLoad(this)"></iframe>

我的phpfile.php的PHP代码:

$coreFiles = Array('blah.jpg', 'blo.png');
# create new zip object
$coreZip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.','');
$coreZip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach($coreFiles as $coreFile){
    # download file
    $download_file = file_get_contents($coreFile);
    #add it to the zip
    $coreZip->addFromString(basename($coreFile),$download_file);
}
# close zip
$coreZip->close();
# send the file to the browser as a download   
header('Content-disposition: attachment; filename=myZipFolder.zip');
header('Content-type: application/zip');
readfile($tmp_file);

您可以使用XMLHttpRequest()fetch()作为Blob获取文件,使用URL.createObjectURL()创建Blob URL,使用Blob URL,将CC_6的引用存储。在后续的click处的元素检查是否定义了Blob URL,如果true,则将Blob URL称为第一个参数,"_self"为第二个参数。该方法应将文件的单个副本存储在客户端浏览器中,为Blob URL,直到用户关闭document创建参考。

html

<button>download</button>

javascript

let url = w = void 0;
document.querySelector("button").addEventListener("click", e => {
  if (url) {
    w = window.open(url, "_self")
  } 
  else {
    fetch("phpfile.php")
    .then(response => response.blob())
    .then(blob => {
      url = URL.createObjectURL(blob);
      w = window.open(url, "_self")
    })
    .catch(err => console.error(err));
  }
});

不支持fetch()

let url = w = void 0;
document.querySelector("button").addEventListener("click", e => {
  if (url) {
    w = window.open(url, "_self")
  } 
  else {
    let request = new XMLHttpRequest();
    request.open("GET", "phpfile.php", true);
    request.responseType = "blob";
    request.onload = () => {
      url = URL.createObjectURL(request.response);
      w = window.open(url, "_self")
    }
    request.onerror = err => console.error(err);
    request.send(null);
  }
});

最新更新