目前,我有以下代码,允许我当时只将一个图像上传到服务器。 但我想要做的是上传多张图片。我不介意它是否会向服务器发送多个请求,但我想替换以下代码,以便我可以一次拖放或选择多个图像并使用ajax发送它。我怎样才能做到这一点?
我尝试使用我在网上找到的一些库,例如dropzone.js,但似乎它没有做到这一点。一些简单的样品或提示会很棒!我很乐意听到你的消息!
HTML代码
<div>
<input type="file" name="mydata[]"/>
<span class="btn" onclick="imgToMyServer('$(this));">Fly Me to the Server ! </span>
</div>
JS方面
<script>
function imgToMyServer(ob) {
var form = $('<form />');
var files = ob.prev('input[type="file"]');
var simplefile = files.prop('files')[0];
var Myname = simplefile.name;
var input = $('<input name="mydata[][my_path]" value="path/' + Myname+ '"/>');
switch (simplefile.type) {
case "image/jpeg":
break;
case "image/png":
break;
case "image/gif":
break;
default:');
return false;
break;
}
files.after(files.clone());
files.appendTo(form);
input.appendTo(form);
datas = new FormData(form[0]);
$.ajax({
type: 'post',
processData: false,
contentType: false,
data: datas,
url: "https//www.sample.com/uploads_my_images",
async: true,
success: function (res) {
//Just happy
}
});
}
</script>
答案 0 :(得分:0)
首先你需要在文件输入类型上添加multiple
属性,以便它可以选择多个文件。
然后,您需要检查所选图像的数量,然后遍历所选图像数组,然后将图像动态附加到表单数据:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div>
<input type="file" name="mydata[]" id ="multiFiles" multiple="multiple">
<button id="upload" class="btn">Fly Me to the Server !</button>
<div id="msg"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#upload').on('click', function (e) {
e.preventDefault();
var form_data = new FormData(); //create form data object
var num_files = document.getElementById('multiFiles').files.length;
for (var x = 0; x < num_files; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]); //append the files to the form data object
}
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, could be json,html
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
服务器:
<?php
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
}
}
}
} else {
echo 'Please choose at least one file';
}
注意:我没有对上传的文件进行任何验证,我刚上传 直接,您需要在客户端和服务器端进行验证。