gpt4 book ai didi

php - 使用 PHP 上传多个文件

转载 作者:行者123 更新时间:2023-11-29 02:47:28 24 4
gpt4 key购买 nike

我有以下代码将文件上传到 mysql 中的数据库:

索引.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
}
?>

上传.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
}
}
?>

效果很好,但仅适用于单个文件。我看了很多教程,但我无法修改代码以允许一次上传多个文件。有什么建议吗?

最佳答案

要允许多个文件上传,您需要在名称为 file[] 的文件输入上设置属性 multiple="multiple"。或者您也可以使用名称为 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];
}

关于php - 使用 PHP 上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40187455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com