我正在尝试创建一个网站来上传和下载任何类型的文件。首先,我创建了一个名为upload
的数据库,这是表的代码:
CREATE TABLE IF NOT EXISTS `files` ( `id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`type` varchar(30) NOT NULL,
`size` int(11) NOT NULL,
`content` mediumblob NOT NULL,
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;
这是我的PHP代码,用于上传文件:
<?php
if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if (!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
}
$conn = mysqli_connect("localhost","root","","upload");
$query = "INSERT INTO files (name, size, type, content ) VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysqli_query($conn,$query) or die('Error, query failed');
$_SESSION['submit']='true';
//echo "
//File $fileName uploaded
//";
header('Location: '.$_SERVER['PHP_SELF'].'?1');
$conn -> close();
}
?>
当我尝试下载时,一切正常,但是当我打开文件时它已损坏,我不明白为什么。这是HTML页面中使用的代码。我试图在一个简单的页面中使用PHP脚本,它的工作原理。但是当我将它添加到我的网站时,它不起作用。
<?php
$conn = mysqli_connect("localhost","root","","upload");
if (isset($_GET['id'])) { // se l'id esiste allora prendi il file dal database
$id = $_GET['id'];
$query = "SELECT name, type, size, content FROM files WHERE id = $id";
$result = mysqli_query($conn,$query) or die('Error, query failed');
list($name, $type, $size, $content) =
mysqli_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content; exit;
}
$query = "SELECT files.id, files.name FROM files";
$result = mysqli_query($conn,$query) or die('Error, query failed');
if (mysqli_num_rows($result) == 0) {
echo "<p>Il tuo database e' vuoto !</p>";
} else {
echo "<div class='box alt'>";
echo "<div class='row uniform 50%'>";
while (list($id, $name) = mysqli_fetch_array($result)) {
?>
<div class="4u">
<span class="image fit"><img src="images/pic02.jpg" alt="" /></span><h3><?php echo $name; ?></h3>
<ul class="actions">
<li><a href="index.php?id=<?php echo $id;?>" class="button">Download</a></li>
</ul>
</div>
<?php }} ?>