我想使用 jQuery 创建一个多文件文件上传器。
下面是我正在使用的代码。我只是想抽象出使用 jQuery(和 File API)和 PHP 一次上传多个文件的要点。如果有人有简化的答案,请随时分享或提供建议。
不过,现在这段代码可以上传图片(有点)。有问题:
- 即使选择了多个文件,也只有一个文件上传到目录
- 表单在提交时更改页面
这是我正在使用的 js/jquery:
function html5Upload($form) {
file = $form.data('input');
if (file) {
var fd = new FormData();
fd.append($form.find(selector).attr('name'), file);
//get other form input and append to formData
$form.find(':input').each(function () {
if (this.type != 'file') {
fd.append($(this).attr('name'), $(this).val());
}
});
//Upload using jQuery AJAX
jqxhr = $.ajax({
url: $form.attr('action'),
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function () {
alert("Images Uploaded!");
}
});
}
$form.remove();
}
$('form').submit(function (event) {
event.preventDefault();
html5Upload($('form.mupload'));
return false;
});
HTML
<form class="mupload" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="userfile" class="fileUpload" multiple>
<button type="submit">Upload</button>
</form>
PHP
/*
Easy PHP Upload - version 2.32
A easy to use class for your (multiple) file uploads
Copyright (c) 2004 - 2010, Olaf Lederer
*/
include("easy_upload/upload_class.php");
$upload = new file_upload();
$upload->upload_dir = 'uploads/';
$upload->extensions = array('.png', '.jpg', '.zip', '.pdf'); // specify the allowed extensions here
$upload->rename_file = true;
if(!empty($_FILES)) {
$upload->the_temp_file = $_FILES['userfile']['tmp_name'];
$upload->the_file = $_FILES['userfile']['name'];
$upload->http_error = $_FILES['userfile']['error'];
$upload->do_filename_check = 'y'; // use this boolean to check for a valid filename
if ($upload->upload()){
echo '<div id="status">success</div>';
echo '<div id="message">'. $upload->file_copy .' Successfully Uploaded</div>';
//return the upload file
echo '<div id="uploadedfile">'. $upload->file_copy .'</div>';
} else {
echo '<div id="status">failed</div>';
echo '<div id="message">'. $upload->show_error_string() .'</div>';
}
}