Фактически элемент управления по умолчанию <input type="file">
позволяет одновременно выбирать один файл, поэтому вы можете загружать только один файл за раз. Тем не менее, я недавно встретил требование разрешить пользователям выбирать папку и загружать файлы в эту папку (один за другим), и я нахожу решение (извините, но я не сохранил URL-адрес решения). Вот что я делаю:
HTML:
<div>
<input type="file" id="files" name="files[]" multiple="" webkitdirectory="">
<div>
<input type="submit" value="Upload" class="btn btn-warning pull-left" onclick="uploadFiles()">
<small class="pull-left result_text">Choose a file folder which only contains image files.</small>
<div class="clearfix"></div>
</div>
<div id="output"></div>
</div>
Javascript:
<script type="text/javascript">
var File_Lists;
window.onload = function(){
var output = document.getElementById('output');
// Detect when the value of the files input changes.
document.getElementById('files').onchange = function(e) {
// Retrieve the file list from the input element
File_Lists=e.target.files;
// Outputs file names to div id "output"
output.innerText = "";
var MAX_ROWS=5;
var filenum=File_Lists.length;
for (i=0; i<Math.min(filenum, MAX_ROWS); i++){
output.innerText = output.innerText + e.target.files[i].webkitRelativePath+"\n";
}
if(filenum>MAX_ROWS){
output.innerText = output.innerText + " and other "+(filenum-MAX_ROWS)+" files...";
}
}
}
function uploadFiles(){
var files=File_Lists;
// Create a new HTTP requests, Form data item (data we will send to the server) and an empty string for the file paths.
xhr = new XMLHttpRequest();
data = new FormData();
paths = "";
// Set how to handle the response text from the server
xhr.onreadystatechange = function(ev){
//handle with server-side responses
};
// Loop through the file list
for (var i in files){
// Append the current file path to the paths variable (delimited by tripple hash signs - ###)
paths += files[i].webkitRelativePath+"###";
// Append current file to our FormData with the index of i
data.append(i, files[i]);
};
// Append the paths variable to our FormData to be sent to the server
// Currently, As far as I know, HTTP requests do not natively carry the path data
// So we must add it to the request manually.
data.append('paths', paths);
// Open and send HHTP requests to upload.php
xhr.open('POST', "process_upload_photo.php", true);
xhr.send(this.data);
}
Я использую PHP для серверной стороне. Вы можете получить пути к файлу со следующим кодом и выполнять аналогичные действия, так как он загружает один файл.
$paths = explode("###",rtrim($_POST['paths'],"###"));
Таким образом, вы можете выбрать несколько файлов с типичным по умолчанию файлом ? Насколько мне известно, вы можете выбирать только один файл за раз с ним и одновременно отправлять этот файл. – mrmoment
Я хочу сделать что-то вроде этого, http://hayageek.com/docs/jquery-upload-file.php, однако я не понимаю, как это понимать, и плагин, который не соответствует моей потребности в 100 % –