我正在使用表单供用户将文件上传到我的网站。我想让他们一次上传多张照片,所以我使用HTML5“多重”属性。
我的HTML:
<form method="post" action="save.php">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="submit"/>
</form>
save.php:
<?php
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
但是,由于某种原因,当我运行脚本时,我收到一个错误,说明未定义索引:上传。并且有一个错误说我为foreach()提供了一个无效的参数。我有什么不对的?
由于
更新
好的,设置enctype="mulitpart/form-data"
有效。现在,我在移动文件时遇到了麻烦。我收到错误move_uploaded_file() expects parameter 1 to be string, array given
。我在这里做错了什么?
再次感谢
答案 0 :(得分:5)
您需要正确的enctype
才能上传文件。
<form method="post" enctype="multipart/form-data" action="save.php">
答案 1 :(得分:0)
试试这个HTML代码:<form method="post" action="save.php" enctype="multipart/form-data">
然后在PHP中:
if(isset($_FILES['uploads'])){
foreach ($_FILES['uploads']['name'] as $file) {
echo $file . "<br/>";
$file= time() . $_FILES['uploads']['name'];
$target= UPLOADPATH . $file;
move_uploaded_file($_FILES['uploads']['tmp_name'], $target)
or die('error with query 2');
}
} else {
echo 'some error message!';
}
答案 2 :(得分:0)
要首先上传文件,您需要在enctype="multipart/form-data"
代码上<form>
。
但是,当您上传多个文件时,$_FILES['uploads']
中的每个键都是一个数组(就像$_FILES['uploads']['name']
)。
循环时需要获取数组键,以便处理每个文件。有关更多详细信息,请参阅docs for move_uploaded_file
。
<?php
foreach ($_FILES['uploads']['name'] as $key=>$file) {
echo $file."<br/>";
$file = time().$file;
$target = UPLOADPATH.$file;
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die('error with query 2');
}
答案 3 :(得分:0)
的index.html
<form method="post" action="save.php" enctype="multipart/form-data">
<input type="file" name="uploads[]" multiple="multiple" />
<input type="submit" name="submit" value="Upload Image"/>
</form>
save.php
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['uploads']['name']); $x++) {
$file_name = time() . $_FILES['uploads']['name'][$x];
$file_tmp = $_FILES['uploads']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name;
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>