J'ai conçu un formulaire simple qui permet à l'utilisateur de télécharger des fichiers sur le serveur. Initialement, le formulaire contient un bouton "parcourir". Si l'utilisateur souhaite télécharger plusieurs fichiers, il doit cliquer sur le bouton "Ajouter d'autres fichiers", ce qui ajoute un autre bouton "Parcourir" dans le formulaire. Lorsque le formulaire est soumis, le processus de téléchargement de fichier est géré dans le fichier 'upload.php'. Cela fonctionne parfaitement pour le téléchargement de plusieurs fichiers. Maintenant, je dois soumettre le formulaire en utilisant '.submit ()' de jQuery et envoyer une demande ajax ['.ajax ()'] au fichier 'upload.php' pour gérer le téléchargement du fichier.
Voici mon formulaire HTML:
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Voici le JavaScript:
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Voici le code pour le traitement du téléchargement de fichier:
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Toute suggestion sur la manière dont je devrais écrire ma fonction '.soummit ()' sera vraiment utile.
Enfin, j'ai trouvé la solution en utilisant le code suivant:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
pour le téléchargement ajax
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Veuillez utiliser le script ci-dessus pour l'envoi ajax. Ça va marcher
Ma solution
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});
En utilisant ce code source, vous pouvez télécharger plusieurs fichiers tels que Google par un à travers ajax. Aussi, vous pouvez voir la progression du téléchargement
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
}
})
.success(function(res,status) {
if(status == 'success'){
percent = 0;
$('#prog'+cl).text('');
$('#prog'+cl).text('--Success: ');
if(cl < ttl){
uploadajax(ttl,cl+1);
}else{
alert('Done ');
}
}
})
.fail(function(res) {
alert('Failed');
});
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);