简体   繁体   中英

Unexpected token < in JSON at position 0 tinymce

This question is asked many times and all of them in a different way that's why I doubt my problem was addressed in them.

I use TinyMCE with a file uploader. If I use an URL it works because it can get it back from the internet. When I want to use an image in a folder it will upload it's image in TinyMCE with on top the box saying "Image uploading: 100%" . But this message stays on top and when I post the content everything but the image will be sent. Looking back I noticed no content in the file directory where I want to place all the uploaded images. Also, it gave back an error.

Unexpected token < in JSON at position 0: Looked up at the error and found something funny. It showed the path where the content goes.

move_uploaded_file(this_is_the_path/this_is_the_image.jpg)

Well in this example it looks fine but in dev tools, the path is indicated as orange which is a string but the file is in black. Does here lies the problem? I wrapped it in a string and obvious result was:

move_uploaded_file(this_is_the_path/'this_is_the_image.jpg')

Which is obviously wrong.

2 side problems which are related but aren't important at the moment to count as a problem.

If I change certain parts. Not sure which. It goes from error located to VM'random number' to frontpage where the action is happening.

files who start with numbers doesn't get uploaded at all and will be messaged as error: 500.

After the main problem is solved I will look into that.

My PHP code for handling the path.

<?php
    $accepted_origins = array("http://localhost:8080");
    $imageFolder = "uploaded_content_frontpage/";
    reset ($_FILES);
    $temp = current($_FILES);
    if (is_uploaded_file($temp['tmp_name'])){
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            } else {
                header("HTTP/1.0 403 Origin Denied");
                return;
            }
        }

// Sanitize input
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
            header("HTTP/1.0 500 Invalid file name.");
            return;
        }

// Verify extension
        if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
            header("HTTP/1.0 500 Invalid extension.");
            return;
        }

      // Accept upload if there was no origin, or if it is an accepted origin
        $filetowrite = 'uploaded_content_frontpage/'.$temp['name'];
        move_uploaded_file($temp['tmp_name'], $filetowrite);

        echo json_encode(array('location' => $filetowrite));
   } else {
        // Notify editor that the upload failed
        header("HTTP/1.0 500 Server Error");
   }
?>

Is the pathing wrong or is it a typo or is it something else?

$(document).ready(function() {
tinymce.init ({
        theme: 'modern',
        selector: '.add_body_structure',
        height: 1000,
        menubar: true,
        branding: false,
        toolbar: 'undo redo | styleselect bold italic forecolor backcolor fontselect fontsizeselect | link paste | alignleft aligncenter alignright alignjustify | outdent indent bullist numlist | removeformat | insert',
        plugins: ' contextmenu print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media mediaembed template table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help autoresize noneditable', 
        contextmenu: 'paste link image inserttable cell row column deletetable',
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'lower-alpha,lower-roman,upper-alpha,upper-roman',
        statusbar: false,
        browser_spellcheck: true,
        image_title: true,      
        automatic_uploads: true,
        media_live_embeds: true,
        contextmenu: true,
        relative_urls: false,
        remove_script_host: false,
        paste_data_images: true,
        encoding: 'xml',
        invalid_elements: 'script, input, textarea, textfield, col, colgroup, caption, dir, meta, object, select, option, source, title',
        fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 28pt 30pt 32pt 34pt 36pt 38pt 40pt',
        images_upload_url: '/wysiwyg/tinymce_main/wysiwyg_one_page_version2.1/views/home/code_for_images/image_uploader.php',

        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*, audio/*, video/*');

            input.onchange = function() {
                var file = this.files[0];

                var reader = new FileReader();
                reader.onload = function () {

                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);
                    // call the callback and populate the Title field with the file name
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };
        input.click();
        }

});
});     

Warning: move_uploaded_file(uploaded_content_frontpage/blobid1510920245387.jpg): failed to open stream: No such file or directory in C:\\wamp\\www\\wysiwyg\\tinymce_main\\wysiwyg_one_page_version2.1\\views\\home\\code_for_images\\image_uploader.php on line 45

Line 45 indicates to move_uploaded_file($temp['tmp_name'], $filetowrite);

As you can see I can't open stream because no such file is in my directory.

Comment out

echo $filetowrite;

and check, because the filepath is being echoed out before your json, and that is what is causing the JSON parsing error. Also there is an extra '.' in your

$filetowrite = 'uploaded_content_frontpage/'.$temp['name'].(see here);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM