tinymce与Laravel图片上传
最近在做Laravel中集成tinymce编辑器,选择tinymce的原因是因为对表格等方面的支持比较方便一些。
但是遇到了图片上传的难题,用了若干天来想办法,甚至想过用axios代替xhr,不过最后还是用xhr解决了问题。
下面贴一下代码:
<script>
tinymce.init({
selector: '#content',
height: 800,
plugins: [
'advlist autolink link image lists charmap preview hr anchor ',
'searchreplace wordcount visualblocks visualchars code fullscreen media ',
'save table directionality template paste'
],
toolbar1: "bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | forecolor backcolor | outdent indent blockquote | bullist numlist ",
toolbar2: "formatselect | link unlink anchor image media | table | hr removeformat | subscript superscript | charmap preview code searchreplace",
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '{{route("image.upload")}}');
var token = '{{ csrf_token() }}';
xhr.setRequestHeader("X-CSRF-Token", token);
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
},
menubar: false,
toolbar_items_size: 'small',
language: 'zh_CN',
});
这里面的重点就是要设置csrf。