如何使用PHP,jQuery和AJAX上传多个文件

我devise了一个简单的表单,允许用户将file upload到服务器。 最初,表单包含一个“浏览”button。 如果用户想要上传多个文件,他需要点击“添加更多文件”button,在表格中添加另一个“浏览”button。 提交表单时,file upload过程在“upload.php”文件中处理。 它可以很好地上传多个文件。 现在我需要通过使用jQuery的'.submit()'提交表单,并发送一个ajax ['.ajax()']请求到'upload.php'文件来处理file upload。

这是我的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> 

这里是JavaScript:

 $(document).ready(function(){ $('.add_more').click(function(e){ e.preventDefault(); $(this).before("<input name='file[]' type='file' />"); }); }); 

这里是处理file upload的代码:

 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 />"; } 

}

任何关于如何编写'.submit()'函数的build议将会非常有用。

最后,我通过使用下面的代码find了解决scheme:

 $('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'/>"); }); }); 

为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. */ 

请使用脚本上面的脚本进行ajax上传。 它会工作

我的解决scheme

  • 假设表单id =“my_form_id”
  • 它从HTML检测表单方法和表单操作

jQuery代码

 $('#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 }); }); 
Interesting Posts