我试图使文件上传到我的web服务器更安全一点,通过编码base64(除了一些其他的事情)。我的最终目标是让客户端单击一个链接,然后php脚本将抓取编码的文件,解码它,然后提示客户端下载解码的文件。我可以将文件解码并存储到一个变量中,但似乎无法将其转换为他们可以下载的东西。这是我到目前为止已经修补在一起的东西,但只是将整个混乱输出到浏览器,而不要求下载文件。
$getFile = file_get_contents('myDoc.pdf');
$fileDecode = base64_decode($getFile);
header('Content-Description: File Transfer');
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="finishedFile.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo $fileDecode;
尝试这样设置内容类型:
http://yogeshchaugule.com/blog/2013/how-display-pdf-browser-php同时,确保php文件的末尾没有空行来响应pdf文本。
如果您希望用户在浏览器中执行操作,则需要JS提供一些帮助。这可能是实现它的最简单的方法,但最好是通过ajax实现对完全不同的php文件的调用,然后触发下载。无论如何:
<?
// check that the post params have been set
if(isset($_GET['f'])){
// get parameter from query string and decode the filename
$file = base64_decode($_GET['f']);
// return the file after checking that it exist
if (file_exists($file)) {
// load the files contents
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
$err = "Oops. That file does not exist.";
}
}else{
// check for download errors
$err = "false";
}
?>
<html>
<head>
<script>
var err = "<? echo $err; ?>";
if(err !== "false"){
alert(err);
}
function download(file){
if (confirm('You are about to download the "'+atob(file)+'". Would you like to continue?')) {
var url = window.location.href.split('?')[0]+"?f="+file;
window.location = url;
} else {
// do nothing. they said no.
}
}
</script>
</head>
<body>
<button onclick="download('dGVzdC5wbmc=')">Download File</button>
</body>
</html>
这里假设文件名为test.png,但只要base 64是正确的,您可以将其更改为任何名称