我在我的web服务器的非公共文件夹中有一个zip文件。我想让公众无法访问该文件,因此我正在寻找使用php readfile来读取zip文件并从javascript中的zip文件创建一个File对象。我不确定这是否是执行此类操作的最佳方式,但希望得到任何建议。从非公开文件夹获取zip文件(php)
如何使用返回的数据构造File对象?
这里是我的PHP代码(getZipFile.php):
<?php
$filename = "abc.zip";
$filepath = "/path/to/zip/";
// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
$buffer = readfile($filepath . $filename);
echo $buffer;
?>
这里是我的javascript代码
$.ajax({
url: 'getZipFile.php',
error: function(e) {
console.log(e);
},
dataType: 'text',
success: function(data) {
console.log(data);
var parts = [
new Blob([data], {type: 'application/zip'}),
new Uint16Array([33])
];
var f = new File(parts, "myzip.zip");
},
type: 'GET'
});
一个我注意到的事情是个原始的Zip文件的大小为2302个字节,当我在成功函数中打印data.length时,数据长度为2287.它们应该是相同的吗?
嗨,遗憾的是,一行代码是从我原来的代码失踪。我有$ buffer = readfile($ filepath。$ filename);在echo $ buffer之前。它给我的是一个空的回应文本。 –
你可以试试:if(realpath($ filepath。$ filename)){readfile($ filepath。$ filename);} else {throw new Exception('error reading file');} – vincenth
谢谢,我的文件路径不正确并解释了为什么它给出了一个空的响应字符串。应该已经完成了你的建议,并在调用readfile之前检查文件是否存在。 –