我正在尝试构建一个基本的上传表单,将多个文件添加到由PHP处理的文件夹中。
我的HTML代码是:
<form id="form" action="add-files-php.php" method="POST" enctype="multipart/form-data">
<div class="addSection">Files To Add:<br><input type="file" name="files[]" multiple /></div>
<div class="addSection"><input type="submit" name="submit" value="Add Files" /></div>
</form>
要处理的PHP是:
$file_path = "../a/files/article-files/$year/$month/";
foreach ($_FILES['files']['files'] as $file) {
move_uploaded_file($_FILES["file"]["name"],"$file_path");
}
我可以毫无错误地运行PHP,但文件不会被添加到路径文件夹中。
我在哪里错了?
答案 0 :(得分:1)
我的一个项目中实际上有类似的代码。试试吧。
foreach ($_FILES['files']['name'] as $f => $name) {
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path);
}
请看以下页面: http://php.net/manual/en/function.move-uploaded-file.php
编辑: 在您提供的代码中没有任何地方,它是否显示您实际上为文件提供了文件名,您只需引用路径,而不是路径+文件名+扩展名
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path . $name);
将原始代码示例修改为第二个,应该可行。
答案 1 :(得分:1)
迭代<?php
//if record was added in last minute
if($row_cnt...)
echo '<script type="text/javascript">',
'notification();',
'</script>'
;?>
<script>
数组并检查文件是否实际上传到服务器:
$_FILES['files']['error']
您的代码最大的问题是您尝试移动$dest_dir = "../a/files/article-files/$year/$month";
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
// The temporary filename of the file stored on the server
$tmp_name = $_FILES["files"]["tmp_name"][$key];
$name = basename($_FILES["files"]["name"][$key]);
// Handle possible failure of the move_uploaded_file() function, too!
if (! move_uploaded_file($tmp_name, "$dest_dir/$name")) {
trigger_error("Failed to move $tmp_name to $dest_dir/$name",
E_USER_WARNING);
}
} else {
// Handle upload error
trigger_error("Upload failed, key: $key, error: $error",
E_USER_WARNING);
}
}
而不是$_FILES['files']['name']
。后者是上传到用于存档文件的temporary directory的临时文件的文件名。
P.S。
使用相对路径容易出错。考虑在包含项目根目录的常量的帮助下使用绝对路径,例如:
的config.php
$_FILES['files']['tmp_name']
upload.php的
<?php
define('MY_PROJECT_ROOT', __DIR__);