我对使用AJAX(formdata),PHP上传多个图像有疑问,并将它们保存到Project Folder和Mysql Database中。 我做了一个样本,到目前为止还没有找到明确的答案。
表单HTML:
<div class="form-group row">
<div class="col-xs-4">
<input type="file" class="form-control" id="foto">
<input type="file" class="form-control" id="foto">
<input type="file" class="form-control" id="foto">
</div>
</div>
<div class="form-group row">
<div class="col-xs-4">
<button type="button" class="btn btn-primary" onclick="addImages()">Submit</button>
<button type="reset" class="btn btn-warning" onclick="resetForm()">Reset</button>
</div>
</div>
Ajax功能:
function addImages() {
var formData = new FormData();
var foto = $('#foto').val();
if (foto !== '') {
var file = $('#foto').prop('files')[0];
var ext = foto.split('.').pop();
ext = ext.toLocaleString().toLocaleLowerCase();
if (ext !== 'png' && ext !== 'jpg' && ext !== 'jpeg') {
swal("File yang diupload harus png, jpg atau jpeg");
return false;
}
formData.append('file', file);
}
$.ajax({
type: "POST",
url: getUrl() + "/imageupload",
processData: false,
contentType: false,
data: formData,
success: function (response) {
if (jQuery.trim(response) == true) {
swal({title: "Succeed to upload images", type: "success", showCancelButton: false
}, function () {
location.reload();
});
} else {
swal({title: "Failed to upload images. ", type: "error", showCancelButton: false
}, function () {
location.reload();
});
}
}
});
}
MySQL查询:
function insert_image($db = NULL, $data = array()) {
$SQL = "INSERT INTO image_location (file) VALUES ('" . $data['foto'] . "')";
$db->exec($SQL);
$insert_id = $db->lastInsertId();
return ($insert_id ? TRUE : FALSE);
}
FYI
我在2个不同的文件中写道。文件AJAX函数和HTML表单在一个文件中,而进程数据库在一个单独的文件中,我创建了一个函数,如:
foreach (glob('../model/*.php') as $filename) {
include_once $filename; }
感谢的