javascript - php Uploading multiple files with ajax -
i've managed upload multiple files using current php , html form , wanted fancy bit ajax , automatically submitting form. i've hidden 'file' input , submit button form handeled js (mentioning incase may affect form submission, form submission , i've checked via http headers). ajax section of js use ajax , standard forms, when submit form $_files empty guess i'm not using ajax correctly here? need change in ajax handle file uploads?
$("#add_button").click(function(e) { e.preventdefault(); $("#folder_open_id").trigger("click"); $("#folder_open_id").change(function() { $("#folder_upload").submit(); }); }); $("#folder_upload").submit(function(event) { var formdata = $(this).serialize(); event.preventdefault(); $.ajax ({ url: "index.php", type: "post", data: formdata, success: function(response) { $("#response_div").html(response); }, error: function(response) { alert(response); } }); });
php
if($_server['request_method'] == 'post') { if(!empty($_files['files']['name'][0])) { $files = $_files['files']; define('cpath', $_server['document_root'] . "/uploads/"); $uploaded = array(); foreach($files['name'] $position => $file_name) { $file_temp = $files['tmp_name'][$position]; $file_new = "./uploads/" . $files['name'][$position]; if(move_uploaded_file($file_temp, $file_new)) echo "success"; else echo "fail, temp: " . $file_temp . " new: " . $file_new; } } else echo '<pre>', print_r($_post, 1), '</pre>'; }
so empty($_files['files']['name'][0]
is returning true , print_r($_post) empty seems.
html form
<form id="folder_upload" action="" method="post" enctype="multipart/form-data"> <input type="file" class="hide" name="files[]" id="folder_open_id" multiple directory webkitdirectory mozdirectory/> <input type="submit" class="hide" value="upload" id="folder_open_upload" /> </form>
here js after mephoros answer, $_files array still seems empty:
$.ajax ({ url: "index.php", type: "post", data: new formdata($(this)), processdata: false, contenttype: 'multipart/form-data; charset=utf-8', success: function(response) { $("#response_div").html(response); }, error: function(response) { alert(response); } });
based on preliminary research, utilize formdata , set processing , contenttype false.
$.ajax({ // ... data: new formdata($(this)), processdata: false, contenttype: false, // ... });
sources:
- http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
- http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
see: http://api.jquery.com/jquery.ajax/
see: https://developer.mozilla.org/en-us/docs/web/guide/using_formdata_objects
Comments
Post a Comment