我的 HTML 頁面中的表單具有以下 3 個欄位,可用于上傳 3 個單獨的檔案。
<div class="form-group">
<label>Important Property Documents Upload</label>
<input type="file" id="update_importantdocupload" name="update_importantdocupload" class="form-control" placeholder="Upload a Compressed file will necessary documents included." required>
<div class="form-group">
<label>Important Property Documents Upload</label>
<input type="file" id="add_importantdocupload" name="add_importantdocupload" class="form-control file_upload" placeholder="Upload a Compressed file will necessary documents included." required>
</div>
<div class="form-group">
<label>Property Cover Image</label>
<input type="file" id="add_propertycoverimage" name="add_propertycoverimage" class="form-control file_upload" placeholder="Upload a Cover Image" required>
</div>
<div class="form-group">
<label>Other Property Images</label>
<input type="file" id="add_propertyotherimages" name="add_propertyotherimages" class="form-control file_upload" placeholder="Compress All Property Images and Upload" required>
</div>
上傳檔案后,我使用以下 Javascript 代碼獲取上傳的檔案并將它們附加到表單資料的其余部分。(必須使用類,因為只起草了 1 個 API 代碼來上傳檔案)
let formData = new FormData();
for (let file of document.getElementsByClassName('file_upload').files) {
formData.append("files", file);
}
但這會引發一個錯誤,即這是不可迭代的。
解決此問題的最佳方法是什么?
提前致謝!
uj5u.com熱心網友回復:
getElementsByClassName回傳具有所有給定類名的所有子元素的類陣列物件。參考
重要的關鍵字是array-like……要迭代它,你需要一個真正的陣列。所以你可以使用Array.from()。
然后,對于每個元素,您需要 files 陣列的第一個檔案。
我還使用FormData.getAll()來控制臺記錄結果...
document.getElementById("test").addEventListener("click", function() {
let formData = new FormData();
for (let inputElement of Array.from(document.getElementsByClassName('file_upload'))) {
formData.append("files", inputElement.files[0]);
}
console.log(formData.getAll("files"))
})
<div class="form-group">
<label>Important Property Documents Upload</label>
<input type="file" id="update_importantdocupload" name="update_importantdocupload" class="form-control" placeholder="Upload a Compressed file will necessary documents included." required>
<div class="form-group">
<label>Important Property Documents Upload</label>
<input type="file" id="add_importantdocupload" name="add_importantdocupload" class="form-control file_upload" placeholder="Upload a Compressed file will necessary documents included." required>
</div>
<div class="form-group">
<label>Property Cover Image</label>
<input type="file" id="add_propertycoverimage" name="add_propertycoverimage" class="form-control file_upload" placeholder="Upload a Cover Image" required>
</div>
<div class="form-group">
<label>Other Property Images</label>
<input type="file" id="add_propertyotherimages" name="add_propertyotherimages" class="form-control file_upload" placeholder="Compress All Property Images and Upload" required>
</div>
</div>
<br>
<button id="test">Append to FormData</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479516.html
標籤:javascript html jQuery
