我正在制作一个小型实用系统来将文件上传到服务器,我正在使用 Jquery,Jquery Ajax,PHP,Bootstrap 3,Fontawesome y Formvalidation.io 。
我需要协作才能完成并添加一些功能;到目前为止,我已设法进入进度条,并实时查看剩余的MB数量;
我想执行以下操作:
Nota:我在HTML中复制整个代码这个全包代码AJAX,可链接,无需下载库,只需要路径和文件PHP,应该创建一个文件夹和一个PHP文件使用代码并更改AJAX中的路径。
AJAX代码:
注意:此代码已包含在HTML中。
$.ajax({
beforeSend: function () {
// Show modal
$("#modal_system").modal('show');
},
url: 'ajax/1.4_ajax.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
timeout: 120000,
xhr: function() {
myXhr = $.ajaxSettings.xhr();
console.log('XHR: ', myXhr);
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function(e){
var loaded = e.loaded;
var total = e.total;
var percentComplete = Math.round((e.loaded / e.total) * 100);
// Quantity of bytes per second
var leftover_bytes = total - loaded;
var leftover_bytes = leftover_bytes / 1048576;
$('.modal-body #dataResponse').html( leftover_bytes.toFixed(2) + ' MB' );
// Progress bar function
$('.progress .progress-bar').css('width', percentComplete + '%');
$('.progress .progress-bar').html( percentComplete + '%');
}, false);
myXhr.upload.addEventListener('load', function(e){
// After upload cant reset progrees bar
//$('.progress .progress-bar').css('width', '0%');
//$('.progress .progress-bar').html( '');
}, false);
}
return myXhr;
}
})
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Upload files Jquery Ajax - XHR2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/formvalidation/formvalidation.io/master/vendor/formvalidation/css/formValidation.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
</head>
<body>
<!-- Header -->
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">Main</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<!--/ Header -->
<!-- Upload file -->
<div class="container">
<div class="row">
<div class="col-xs-12">
<form action="" method="post" name="form" id="form" enctype="multipart/form-data">
<div class="row">
<div class="col-xs-12">
<h1>Upload files</h1>
</div>
<div class="col-xs-12">
<div class="form-group">
<input type="file" name="image" id="image" class="form-control" multiple>
</div>
</div>
<div class="col-xs-12">
<button type="submit" name="upload" class="btn btn-primary">Upload</button>
<p id="response"></p>
</div>
</div>
</form>
</div>
</div>
</div>
<!--/ Upload file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.rawgit.com/formvalidation/formvalidation.io/master/vendor/formvalidation/js/formValidation.min.js"></script>
<script src="https://cdn.rawgit.com/formvalidation/formvalidation.io/master/vendor/formvalidation/js/framework/bootstrap.min.js"></script>
<script>
$(function() {
$('#form').formValidation({
framework: 'bootstrap',
excluded: ':disabled',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
image: {
validators: {
notEmpty: {
message: 'Image field required.'
}
}
}
}
})
.on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation');
formData = new FormData(),
params = $form.serializeArray(),
image = $form.find('[name="image"]')[0].files;
$.each(image, function(i, file) {
// Prefix the name of uploaded files with "docs-"
// Of course, you can change it to any string
formData.append('image[]', file);
});
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
// Info add send post
formData.append('id', Math.random());
$.ajax({
beforeSend: function () {
// Show modal
$("#modal_system").modal('show');
},
url: 'ajax/1.4_ajax.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
timeout: 120000,
xhr: function() {
myXhr = $.ajaxSettings.xhr();
console.log('XHR: ', myXhr);
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function(e){
var loaded = e.loaded;
var total = e.total;
var percentComplete = Math.round((e.loaded / e.total) * 100);
// Quantity of bytes per second
var leftover_bytes = total - loaded;
var leftover_bytes = leftover_bytes / 1048576;
$('.modal-body #dataResponse').html( leftover_bytes.toFixed(2) + ' MB' );
// Progress bar function
$('.progress .progress-bar').css('width', percentComplete + '%');
$('.progress .progress-bar').html( percentComplete + '%');
}, false);
myXhr.upload.addEventListener('load', function(e){
// After upload cant reset progrees bar
//$('.progress .progress-bar').css('width', '0%');
//$('.progress .progress-bar').html( '');
}, false);
}
return myXhr;
}
}).done( function(data, textStatus, jqXHR) { // Before success
$('p#response').html( data.message );
}).fail( function(jqXHR, textStatus, errorThrown) { // Before error
switch(jqXHR.status) {
case 0:
$('p#response').html( 'Timeout exceeded.' );
break;
case 403:
$('p#response').html( 'The session has expired.' );
break;
case 404:
$('p#response').html( 'The requested page does not exist.' );
break;
default:
if(jqXHR.status != 200) {
$('p#response').html( 'Error please try again has occurred.' );
}
break;
}
console.log(jqXHR);
//console.log('Estatus readyState:' + jqXHR.readyState);
//console.log('Estatus status:' + jqXHR.status);
//console.log('Estatus statusText:' + jqXHR.statusText);
//console.log('Estatus responseText:' + jqXHR.responseText);
//console.log('Estatus setRequestHeader:' + jqXHR.setRequestHeader);
});
});
});
</script>
<!-- Modal -->
<div class="modal fade" id="modal_system" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Example</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div><strong>Quantity left: </strong> <span id="dataResponse"></span></div>
</div>
</div>
</div>
</div>
</body>
</html>
PHP代码:
<?php
/**
* Function to organize uploaded files
*/
function organizeArray( $arr ){
foreach( $arr as $key => $all ){
foreach( $all as $i => $val ){
$new[$i][$key] = $val;
}
}
return $new;
}
// Array organized
$image = organizeArray( $_FILES['image'] );
// Configurations
$document_root = $_SERVER['DOCUMENT_ROOT'];
$directory = "../files/";
// Browse array
foreach ($image as $key => $value) {
move_uploaded_file($value['tmp_name'], $directory . '1.2 -' . date('h-i-s') . $value['name']);
}
$data = array(
'response' => true,
'message' => 'Completed'
);
echo json_encode($data);
?>
¡非常感谢您的支持!!
非常感谢