如何使用 PHP 上傳多個檔案並將其儲存在資料夾中?
以下是上傳多個檔案並將它們儲存在資料夾中的步驟 -
- 輸入名稱必須定義為一個數組,即 name="inputName[]"
- 輸入元素應具有 multiple="multiple" 或僅 multiple
- 在 PHP 檔案中,使用語法 "$_FILES['inputName']['param'][index]"
- 必須檢查空檔名稱和路徑,因為該陣列可能包含空字串。為了解決此問題,請在 count 前使用 array_filter()。
以下是程式碼的演示 -
HTML
<input name="upload[]" type="file" multiple="multiple" />
PHP
$files = array_filter($_FILES['upload']['name']); //Use something similar before processing files.
// Count the number of uploaded files in array
$total_count = count($_FILES['upload']['name']);
// Loop through every file
for( $i=0 ; $i < $total_count ; $i++ ) {
//The temp file path is obtained
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//A file path needs to be present
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
//File is uploaded to temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Other code goes here
}
}
}列出檔案,並將需要上傳的檔案數計數儲存在 total_count 變數中。建立臨時檔案路徑,並迭代地將每個檔案放入包含資料夾的此臨時路徑中。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP