我有以下代码将文件上传到mysql中的数据库:
的index.php
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />
<?php
if(isset($_GET['success']))
{
?>
<label>File Uploaded Successfully... <a href="view.php">click here to view file.</a></label>
<?php
}
else if(isset($_GET['fail']))
{
?>
<label>Problem While File Uploading !</label>
<?php
}
else
{
?>
<?php
}
?>
upload.php的
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
效果很好,但仅适用于单个文件。我看过很多教程,但我无法修改代码以允许一次上传多个文件。有什么建议吗?
答案 0 :(得分:1)
要允许多个文件翻录,您需要在名为multiple="multiple"
的文件输入上设置属性file[]
。或者您也可以使用名称为file[]
的单独输入。比在数据库中存储值一样
foreach($_FILES['filename']['name'] as $key=>$name){
// store each file and write data to DB for each file
//for example to get the name of file
$name = $_FILES['filename']['name'][$key];
}