我需要通过浏览器一次上传大量图片(例如200张小图片)。我有这段代码:
<?php
if(isset($_POST['Upload_files']) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo count($_FILES['files']['name']); // Even if I upload more than 20 files, it still displays 20.
$target_directory = "upload/";
foreach ($_FILES['files']['name'] as $file_number => $file_name) {
$file = $_FILES["files"]["tmp_name"][$file_number];
if (mime_content_type($file) != 'image/png' && mime_content_type($file) != 'image/jpeg')
{ $error[] = 'File '.$file_name.' is not in JPG / PNG format!'; continue; }
else
{ if(move_uploaded_file($file, $target_directory.$file_name)) {$count_of_upload_file++;}}
}
}
// If files were uploaded
if($count_of_upload_file != 0){echo 'Your files ('.$count_of_upload_file.' ) were successfully uploaded.';}
// If there was an error
if (isset($error)) {foreach ($error as $display_error) {echo '- '.$display_error.'<br />';}}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
它有效。但是我的提供者将' max_file_uploads '设置为20(我无法更改它)。 (Uploadify扩展程序适用于20多个文件,但我想拥有自己的小解决方案。)所以我认为我需要在这里添加一些内容,而不是一次只上传200个文件200个文件(或者二十岁二十岁。但我不知道该怎么做。 (使用AJAX? - 我从来没用过它,所以我真的不知道。)谢谢!
答案 0 :(得分:0)
如果您不想使用ajax,则需要一个循环来接收文件
for($i = 0; $i < count($_FILES['files']['tmp_name']); $i++){
$tmp = $_FILES['files']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "Uploaded successfully";
}else{
echo "failed";
}
}
在表单中,您必须将所有输入字段命名为files [],例如:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
或者如果您想使用ajax,这是一个例子: Upload multiple image using AJAX, PHP and jQuery