2017-04-21 92 views
0

因此,我创建了一些php代码来使用ZipArchive创建zip文件。这将创建一个zip文件并下载它。要启动下载,我将包含下面php代码的php文件链接放在iframe中。然后将此iframe插入到html文档中。重新下载zip文件而不重写zip文件 - ZipArchive PHP

因此,无论何时加载html文档,下载器都会启动。我在iframe标记中创建了onload属性,它将调用一个函数来显示重新下载按钮。

因此,如果用户单击重新下载按钮,我希望它再次下载同一个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); 
+1

你就必须存储的地方解压缩文件。并在调用ZipArchive之前先查找它。是的,这会在一段时间后占用大量空间 – Forbs

+0

_“因此,无论何时加载html文档,下载程序都会启动”_,_“因此,如果用户单击重新下载按钮”_位于哪里“重新下载按钮”? – guest271314

+0

@ guest271314重新下载按钮将出现在HTML文档中的iframe上方 –

回答

0

您可以使用XMLHttpRequest()fetch()获取文件为Blob,创建Blob URL使用URL.createObjectURL(),存储参考Blob URL。在随后的click元素检查是否定义了Blob URL,如果是true,请拨打window.open()并将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); 
    } 
}); 
+0

blob不适用于safari –

+0

@HoaHo您尝试使用哪个版本的safari? – guest271314

+0

macOS Sierra上的safari v10.0 Sierra –