javascript - Laravel 5.2 ajax upload progress bar and TokenMismatchException in VerifyCsrfToken.php line 67 -
i'm trying integrate progress bar on image upload. code works fine when submit form php, when include javascript progress bar error "tokenmismatchexception in verifycsrftoken.php line 67". form:
{!! form::open(array('files' => true, 'class' => 'form', 'route' => ['backend.posts.uploadimage', $post->id])) !!} <div class="form-group"> {!! form::file('image', ['id' => 'image']) !!} </div> <hr> <input type="button" value="upload image" class="btn btn-info btn-sm" onclick="uploadimage()"> {!! form::close() !!}
this form generate hidden input field token:
<input name="_token" type="hidden" value="jgqwc2gljisezrl8wvfmah490xhoh727345u6hzk">
my javascript code this:
function uploadimage() { var file = document.getelementbyid("image").files[0]; var id = {{ $post->id }}; var formdata = new formdata(); formdata.append("image", file); var ajax = new xmlhttprequest(); ajax.upload.addeventlistener("progress", progresshandler, false); ajax.addeventlistener("load", completehandler, false); ajax.addeventlistener("error", errorhandler, false); ajax.addeventlistener("abort", aborthandler, false); ajax.open("post", "{{ route('backend.posts.uploadimage', $post->id) }}"); ajax.send(formdata); } function progresshandler(event) { var percent = (event.loaded / event.total) * 100; document.getelementbyid("progresspercent").style.width = math.round(percent); } function completehandler(event) { document.getelementbyid("status").innerhtml = event.target.responsetext; document.getelementbyid("progresspercent").style.width = 0; } function errorhandler(event) { document.getelementbyid("status").innerhtml = "upload failed"; } function aborthandler(event) { document.getelementbyid("status").innerhtml = "upload aborted"; }
and method in postcontroller uploading image this:
public function uploadimage(requests\uploadimagerequest $request, $id) { $post = $this->posts->findorfail($id); $image = $request->file('image'); $imagename = $image->getpathname(); $newimagename = $post->id . '-' . md5(microtime()); $imageextension = $image->getclientoriginalextension(); $imagefile = $newimagename . '.' . $imageextension; $path = public_path(); move_uploaded_file($imagename, $path . '/images/img_upload/' . $imagefile); $post->where('id', $id)->update(['image_name' => $newimagename, 'ext' => $imageextension]); return view('backend.posts.uploadimage'); }
how can post token hidden fields using pure javascript, or there other solution solve problem? please help.
use getelementsbyname()
value of input field.
var _token = document.getelementsbyname('_token')[0].value; //and append value form data formdata.append("_token", _token);
Comments
Post a Comment