Uploading files using FormData, AJax and CakePHP -
okay, in all, i'm trying upload single file via ajax using formdata , cakephp form. problem trying grab info error logging $this->request->data in controller returns empty files array.
so, i've set form, using cakephp's helper. construction of isn't relevant. javascript used output whatever debugging need.
so here's setup. have controller called requestscontroller , view name/function upload_files.
the piece of javascript code looks this. note, called when value of file input element changes (i.e 1 time they've selected file upload)
plugin.fileupload = function(el) { el = $(el); form = el.closest('form'); var files = el.get(0).files; console.log(files.length) var formdata = new formdata(); (var = 0; < files.length; i++) { var file = files[i]; console.log(file); formdata.append('files[]', file, file.name); } formdata.append("username", "blablabl@gmail.com"); var xhr = new xmlhttprequest(); xhr.open('post', form.attr('action'), true); xhr.onload = function () { if (xhr.status === 200) { toastr.success('successfully loaded'); } else { alert('an error occurred!'); } }; xhr.send(formdata); console.log(files); console.log(formdata); } excuse console logs. it's purpose of showing output , debugging.
you'll see append username field test post making info intact controller. indeed. here's output logging $this->request->data array:
2014-06-18 17:51:41 error: requestscontroller::upload_files - line 45 2014-06-18 17:51:41 error: array ( [username] => blablabl@gmail.com ) as can see, username field goes through not files.
i've logged files variables in js console , looks great. in firebug looks this:
filelist { 0=file, length=1, item=item(), more...} logging the formdata variable console looks this:
formdata { append=append()} sigh, nil in formdata output suggests files making formdata object.
any ideas??
ah, definite gotcha
accessing uploaded files via formdata in controller accessing files in php script form submission.
it seem that, in order me manipulate these files, needed access them normal $_files variable.
so, logging in controller looks this:
function upload_files() { if($this->request->is('post')) { cakelog::write('error', print_r($_files, true)); } } and nice, healthy looking array of files this:
2014-06-18 22:13:29 error: array ( [files] => array ( [name] => readme.txt [type] => text/plain [tmp_name] => /tmp/phpoutn8l [error] => 0 [size] => 3627 ) ) ajax cakephp-2.0 form-data
No comments:
Post a Comment