我有以下代码用于使用 php 和 mysql 上传多个文件。但是由于某种原因,如果选择了“n”个文件,则似乎只有最后一个(或第“n”个)文件被上传..
以下是各自的文件:
HTML
<form enctype="multipart/form-data" method="post" action="<?php echo htmlentities($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<textarea class="form-control" name="postbox" id="pbox"></textarea>
</div>
<h5><strong>Add media:</strong></h5>
<input type="file" name="pfile[]" multiple="multiple" accept="image/*,audio/*,video/*"><br/>
<button type="submit" class="btn btn-success" name="psubmit">Post!</button>
</form>
<div class="posts">
<?php
if(isset($_POST['postbox'])){
$ps = escape($_POST['postbox']);
}
include_once('includes/uploadfile.php'); ?>
</div>
包括/上传文件.php
<?php ob_start();
require_once 'core/init.php';
if(isset($_POST['psubmit']))
{
foreach ($_FILES['pfile']['tmp_name'] as $key=>$value)
{
$pfname = $_FILES["pfile"]['name'][$key];
$pftype = $_FILES['pfile']['type'][$key];
$pfsize = $_FILES['pfile']['size'][$key];
$pftmploc = $_FILES['pfile']['tmp_name'][$key];
$pferror = $_FILES['pfile']['error'][$key];
$blast = explode(".", $pfname);
$pfextn = end($blast);
if (!empty($ps) && empty($pfname))
{
$dbfname = NULL;
$abc = $get->addPost($a, $ps, $pfname);
header('location:'.escape($_SERVER['PHP_SELF'])); exit;
}
else if (!empty($pfname) && !empty($ps))
{
//list($width, $height) = getimagesize($pftmploc);
if($pfsize > 20971520)
{
echo "ERROR: Your file was larger than 20 Megabytes in size.";
unlink($pftmploc);
exit();
}
else if(!preg_match("/.(gif|jpg|png|mp3|mp4|avi)$/i", $pfname) )
{
echo "ERROR: Restricted file format!Kindly stick to these formats alone:gif,jpg,png,mp3,mp4,avi";
unlink($pftmploc);
exit();
}
else if($pferror == 1)
{ // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
}
$dbfname = rand(100000000000,999999999999).$pfname;
$updir = "ups/posts/";
$arraymov = array();
array_push($arraymov, $dbfname);
$movrslt = move_uploaded_file($pftmploc,$updir.$dbfname);
if($movrslt != true)
{
echo 'ERROR: File upload failed. Try again!';
exit();
}
}
$abc = $get->addPost($a, $ps, implode(',',$arraymov));
header('location:'.escape($_SERVER['PHP_SELF'])); exit;
}
?>
文件上传功能:
public function addPost($user_id,$status,$file_path){
$query = $this->_db->prepare("INSERT INTO postsinitial (puid, pstatus, postimg) VALUES (:k, :l, :m)");
$query->bindValue(':k',$user_id);
$query->bindValue(':l', nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8')));
$query->bindValue(':m',$file_path);
$query->execute();
$rsizes = $query->rowCount();
if ($rsizes > 0) {
return true;
}
else
{
return false;
}
}
我尝试编写代码将每个文件路径作为逗号分隔的值数组插入,以便用户可以为数据库中的一条记录上传多个图像。这很重要!
提前Tnx!