Luka's avatar
Level 1

Tinymce, Vuejs and Image Upload not working

Hi there, I am trying to implement tinymce in my vuejs component and got it finally to work. I use the official TinyMCE Vue component. I now wanted to add an Image Upload and have to admit that I have got no idea how to get it to work. I was hoping that the Image does not get uploaded straight away and that it will just show up in the editor and only when I send of the whole form it will be send. I assumed to get it to work by setting automatic_uploads to false, but the Image does get send straight away and I get the Error 419 which I suppose is the X-CSRF-TOKEN error. I think I am supposed to do all the settings in the init function, but I have got no idea how to access the function. In actual fact I have got no idea at all how this is supposed to work together and hope somebody can point me in the right direction. My current source code is below.

<template>
<div>
<form method="post" action="" @submit.prevent="onSubmit" @keydown="errors.clear()">
    <fieldset class="add-form"><legend class="add-form">
    <h3>Article Details</h3></legend>
   <label class="required" for="fname">Headline</label>
   <input class="form-control"  v-model="post.title" id="fname" placeholder="Headline">
   <span class="invalid-feedback" v-text="errors.get('title')"></span>
   <tinymce v-model="post.body"
        :plugins="myPlugins" 
        :toolbar ="myToolbar1"
        :init="myInit"
    >
 </tinymce>   

</form> 
</div>

</template>

 <script>
 import Editor from '@tinymce/tinymce-vue';
 // Import TinyMCE
 import tinymce from 'tinymce/tinymce';
 // A theme is also required
 import 'tinymce/themes/modern/theme';

 export default{
    components: {
           'tinymce': Editor // <- Important part
    },

    data () { 
            return { 
            name: 'app',
            myModel:'',
            theme: "modern",

            myToolbar1: 'undo redo | bold italic underline preview | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
            myPlugins: "link image code preview imagetools",
           
            myInit: {
                    automatic_uploads: false, 
                    images_upload_url: '/api/upload-image',   
            },
0 likes
1 reply
Luka's avatar
Level 1

Ok, I found a solution, just in case somebody is looking for something similar I will share it here. You have to add the Token so you have to overwrite the images_upload_handler function.

The only issue I have now got is that I create a folder dynamically in the upload method in my controller, but I would like that multiple images in a Post to be saved in the same folder. See the bottom Part which is my Controller. I thought about getting the folder name returned an then adding that into a hidden field but if I add this.folder = json.folder then nothing gets added. Any idea how I could solve this?

data () { 
            return { 
            name: 'app',
           
            myModel:'',
            theme: "modern",
            myToolbar1: 'undo redo | bold italic underline forecolor backcolor | alignleft aligncenter alignright alignjustify | hr bullist numlist outdent indent | link image table | code preview',
            myPlugins: "link image code preview imagetools table lists textcolor hr wordcount",
           
            myInit: {
              
                images_dataimg_filter: function(img) {
        return false;
                    return img.hasAttribute('internal-blob');
                },
                convert_urls : false,
                height:500,
                automatic_uploads: false, 
                images_upload_base_path: '/../../',
                relative_urls : false,

                // override default upload handler to simulate successful upload
                images_upload_handler: function (blobInfo, success, failure,folderName) {
                    var xhr, formData;
                    xhr = new XMLHttpRequest();
                    xhr.withCredentials = false;
                  
                    xhr.open('POST', '/api/upload-image');
                    var token = document.head.querySelector("[name=csrf-token]").content;
                    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);
                   
                }                
            }, 


public function uploadImages()
{
  $folder = uniqid();
  if (!\Storage::exists($folder)) {
        \Storage::disk('posts')->makeDirectory($folder);
  }

  $imgpath = \Storage::disk('posts')->put($folder,request()->file('file'));

  return \Response::json(['folder' => $folder, 'location' => '/storage/uploads/posts/'.$imgpath]);

}

Please or to participate in this conversation.