2016-08-24 80 views
2

我在我的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.它们应该是相同的吗?

回答

1

$ buffer从哪里来? Additionnaly你似乎没有要发送的文件,你应该增加:

echo readfile($filepath . $filename); 

你也可以添加一些控制,以检查文件是否存在,但是这超出了你的问题的范围。

+0

嗨,遗憾的是,一行代码是从我原来的代码失踪。我有$ buffer = readfile($ filepath。$ filename);在echo $ buffer之前。它给我的是一个空的回应文本。 –

+0

你可以试试:if(realpath($ filepath。$ filename)){readfile($ filepath。$ filename);} else {throw new Exception('error reading file');} – vincenth

+0

谢谢,我的文件路径不正确并解释了为什么它给出了一个空的响应字符串。应该已经完成​​了你的建议,并在调用readfile之前检查文件是否存在。 –

1

我结束了使用XMLHttpRequest处理请求和指定blob作为我的返回数据类型。这是我的最终代码。

PHP代码:

<?php 
ob_start(); 
$filename = "abc.zip"; 
$filepath = "/path/to/zip/"; 
$zip = $filepath . $filename; 
header("Content-type: application/zip"); 
header("Content-Length: ".filesize($filepath.$filename)); 
ob_clean(); 
flush(); 
readfile($filepath . $filename); 
exit; 

javascript代码:

var oReq = new XMLHttpRequest(); 
oReq.open("GET", "getZipFile.php", true); 
oReq.responseType = "blob"; 
oReq.onload = function(oEvent) { 
    var data = oReq.response; 
    var f = new File([data], "myzip.zip", { 
     lastModified: new Date(0), 
     type: "application/zip" 
    }); 
}; 
oReq.send();