我正在尝试使用AJAX / jQuery创建上传表单。问题是我无法从单个输入上传多个文件。使用此代码,我可以上传1个文件:
HTML:
<form name="myform" id="myform" enctype="multipart/form-data">
<input name="file[]" type="file" multiple />
<input type="button" value="Upload" />
</form>
jQuery的:
$(document).ready(function(){
$(':button').click(function(){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
dataType:"json",
async: true,
success: function(data) {
console.log(data.Result);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
我将formData
部分更改为:
var formData = new FormData($('input[name^="file"]'));
$.each($('input[name^="file"]')[0].files, function(i, file){
formData.append(i, file);
});
PHP部分:
foreach($_FILES as $index => $file)
{
// for easy access
$fileName = $file['name'];
// for easy access
$fileTempName = $file['tmp_name'];
// check if there is an error for particular entry in array
if(!empty($file['error'][$index]))
{
// some error occurred with the file in index $index
// yield an error here
return false;
}
// check whether file has temporary path and whether it indeed is an uploaded file
if(!empty($fileTempName) && is_uploaded_file($fileTempName))
{
// move the file from the temporary directory to somewhere of your choosing
move_uploaded_file($fileTempName, ROOT_DIR . '/uploads/xPhoto/' . $fileName);
// mark-up to be passed to jQuery's success function.
echo '<p>Click <strong><a href="uploads/' . $fileName . '" target="_blank">' . $fileName . '</a></strong> to download it.</p>';
}
}
所以我的问题是,如何通过单个输入上传多个文件?
答案 0 :(得分:0)
您可能需要在文件中包含索引:
formData.append(i, file[i]);
答案 1 :(得分:0)
这对我有用。让我们从单个输入上传多个文件。所有都可以从PHP中的$ _FILES
全局访问。
var formData = new FormData();
var files = $('#files_input').prop('files');
$.each(files, function(i, file) {
formData.append("file_" + i, file);
});