我是 PHP 代码的新手。目前我正在创建一个关于文件上传/下载的项目,用户可以在其中登录并在他们的帐户中上传-存储-下载文件。
我的问题是,如何让用户上传的文件可以下载?我的意思是,每个上传文件的下载链接?这里有人可以为我建议一个代码吗?
到目前为止,我已经成功上传了代码并列出了成功上传的文件。下面是已经完成的代码,供大家帮我编写下载功能的代码。
//code for listing uploaded files in "userpage.php"
<div class="box6">
<h3>File Lists</h3>
<?php
$username = $_SESSION['UserName'];
if($handle = opendir('users/'.$username.'/')){
while(false !== ($entry = readdir($handle))){
if($entry != "." && $entry != ".."){
echo "$entry<br>";
}
}
closedir($handle);
}
?>
<table width="650">
<tr>
<td>
<?php echo $entry ;?>
</td>
</tr>
</table>
//code for uploading files after users press the upload button
<?php
require("connection.php");
session_start();
$username = $_SESSION['UserName'];
$udir= "users/".$username."/";
$ufile = $udir . basename($_FILES['file']['name']);
$file = ($_FILES['file']['name']);
mysql_query("UPDATE `users` SET `Files` = '$file'") ;
if(move_uploaded_file($_FILES['file']['tmp_name'], $ufile)){
header('location:uploadfiles.php?feedback3=uploadsuccessful');
}
else{
header('location:uploadfiles.php?feedback3=uploaderror');
}
?>
非常感谢您。
最佳答案
来自 PHP 手册:http://us1.php.net/fpassthru
<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
如果您不希望为每种文件类型提供一个,您可能希望使用 application/octet-stream
作为 Content-Type
。
同时提供 Content-Disposition
将强制浏览器显示或下载图像文件和其他可以显示的文件。
关于php - 如何在 PHP 中为上传的文件创建下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20311947/