多文件上傳的兩種情況
①使用多個name值
<input type="file" name="file1"><input type="file" name="file2"><input type="file" name="file3"><input type="file" name="file4">
a.點擊提交之后接收到的數(shù)據(jù)格式
Array([file1] => Array([name] => 8.png[type] => image/png[tmp_name] => G:/wamp/tmp/php737.tmp[error] => 0[size] => 200)[file2] => Array([name] => 28.png[type] => image/png[tmp_name] => G:/wamp/tmp/php738.tmp[error] => 0[size] => 6244)[file3] => Array([name] => 54a296f8n6787b34c.png[type] => image/png[tmp_name] => G:/wamp/tmp/php739.tmp[error] => 0[size] => 3143)[file4] => Array([name] => 54c0573dncb4db6f7.jpg[type] => image/jpeg[tmp_name] => G:/wamp/tmp/php788.tmp[error] => 0[size] => 5404))
從這種格式可以看出來,每一個文件對應(yīng)一個數(shù)組單元
所以使用foreach遍歷數(shù)組,并對每個數(shù)組單元進行文件上傳函數(shù)調(diào)用
b.點擊提交后的操作
①接收上傳的文件信息
$file = $_FILES;
②引入上傳函數(shù)
include('./functions.php');
③設(shè)置文件保存路徑
$path = './uploads/'; // 此目錄需要手動創(chuàng)建
④調(diào)用文件上傳函數(shù)
foreach($file as $v){$info = uploadFile($v,$path);⑤判斷上傳狀態(tài)if($info['isok']){echo '上傳成功'.$info['message'];} else {echo '上傳失敗'.$info['message'];}}
---------------------------------------------------------------
②使用單個name值
a.第一種寫法
<input type='file' name="file[]"><input type='file' name="file[]"><input type='file' name="file[]">
b.第二種寫法
<input type="file" name="file[]" multiple>
c.點擊提交之后,接收到的數(shù)據(jù)格式
Array([userpic] => Array([name] => Array([0] => 8.png[1] => 9b2d7581fba543ec9bcf95e91018915a.gif[2] => 12.jpg)[type] => Array([0] => image/png[1] => image/gif[2] => image/jpeg)[tmp_name] => Array([0] => G:/wamp/tmp/php85E5.tmp[1] => G:/wamp/tmp/php85E6.tmp[2] => G:/wamp/tmp/php8635.tmp)[error] => Array([0] => 0[1] => 0[2] => 0)[size] => Array([0] => 200[1] => 16503[2] => 19443)))
從這種格式可以看出來,是將上傳的文件信息分開保存到每個下標(biāo)中。
所以要做的事情就是拼接出來一個完整的文件信息,一個一維數(shù)組
Array([name] => 54c0573dncb4db6f7.jpg[type] => image/jpeg[tmp_name] => G:/wamp/tmp/php788.tmp[error] => 0[size] => 5404)
所以要進行的操作,是遍歷$_FILES['file'] 然后從中取出每條上傳文件的信息
d.點擊提交后的操作
①接收上傳的文件信息
$file = $_FILES['file'];
②引入上傳函數(shù)
include('./functions.php');
③設(shè)置文件保存路徑
$path = './uploads/'; // 此目錄需要手動創(chuàng)建
④調(diào)用文件上傳函數(shù)
foreach($file['name'] as $key=>$value){$data['name'] = $file['name'][$key];$data['type'] = $file['type'][$key];$data['tmp_name'] = $file['tmp_name'][$key];$data['error'] = $file['error'][$key];$data['size'] = $file['size'][$key];$info = uploadFile($data,$path);
⑤判斷上傳狀態(tài)
if($info['isok']){echo '上傳成功'.$info['message'];} else {echo '上傳失敗'.$info['message'];}}
a.遍歷$file['name'] 只是為了獲取$key
b.每遍歷一次,取出相對應(yīng)下標(biāo)的文件信息,賦值給一個新數(shù)組中對應(yīng)的鍵
如第一次 $key = 0;
$data['name'] = $file['name'][0]; // 相當(dāng)于取出了第一個文件的名字$data['type'] = $file['type'][0]; // 相當(dāng)于取出了第一個文件的類型
...
第一次遍歷完成之后
$data = array([name] => 54c0573dncb4db6f7.jpg[type] => image/jpeg[tmp_name] => G:/wamp/tmp/php788.tmp[error] => 0[size] => 5404);
這樣就取出了第一個文件的所有信息
然后調(diào)用上傳函數(shù),進行文件上傳處理
第二次遍歷時$key=1,相當(dāng)于獲取第二個上傳文件的信息