-
falcon812311 I can use google
 
-
Posts: 26
Threads: 13
Joined: Sep 2016
Reputation:
0
Hi guys,
I need some help, I have problem with Tinymce version 4.9.8 upload image. I follow from this official guide ( https://www.tiny.cloud/docs-4x/general-c...agehandler)
This is my script from view
Code: <?= script_tag('assets/tinymce/tinymce.min.js'); ?>
<script>
tinymce.init({
selector: 'textarea#post_content',
plugins: 'image code media',
toolbar: 'undo redo | styleselect | bold italic underline | link image media | code',
menubar: false,
document_base_url: '<?= base_url() ?>',
images_upload_handler: function (blobInfo, success, failure, progress) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '<?= base_url('admin/blog/imgUpload') ?>');
xhr.upload.onprogress = function (e) {
progress(e.loaded / e.total * 100);
};
xhr.onload = function() {
var json;
if (xhr.status < 200 || xhr.status >= 300) {
failure('HTTP Error: ' + xhr.status);
return;
}
// console.log(xhr.responseText);
json = JSON.parse(xhr.responseText);
// console.log(json.location);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
xhr.onerror = function () {
failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
</script>
2. Controller code:
PHP Code: public function blogImgUpload() { $accepted_origins = array('http://localhost:8080'); $imageFolder = "../public/blog_img/";
reset ($_FILES); $temp = current($_FILES); if (is_uploaded_file($temp['tmp_name'])){ if (isset($_SERVER['HTTP_ORIGIN'])) { // same-origin requests won't set an origin. If the origin is set, it must be valid. if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } else { header("HTTP/1.1 403 Origin Denied"); return; } }
/* If your script needs to receive cookies, set images_upload_credentials : true in the configuration and enable the following two headers. */ // header('Access-Control-Allow-Credentials: true'); // header('P3P: CP="There is no P3P policy."');
// Sanitize input if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) { header("HTTP/1.1 400 Invalid file name."); return; }
// Verify extension if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) { header("HTTP/1.1 400 Invalid extension."); return; }
// Accept upload if there was no origin, or if it is an accepted origin $filetowrite = $imageFolder . $temp['name']; move_uploaded_file($temp['tmp_name'], $filetowrite);
// Respond to the successful upload with JSON. // Use a location key to specify the path to the saved image resource. // { location : '/your/uploaded/image/file'} // $img = [ // 'location' => base_url('blog_img/') . $temp['name'] // ]; $img = [ 'location' => $filetowrite ]; // echo $this->response->setJSON($img); return json_encode($img); } else { // Notify editor that the upload failed header("HTTP/1.1 500 Server Error"); }
Routes.php settings
PHP Code: $routes->group('admin', function($routes){ ... $routes->add('blog/imgUpload', 'Admin\BlogManagement::blogImgUpload'); .. });
1) The file is successfully upload at `blog_img/` directory
2) I receive error in chrome console
PHP Code: Uncaught SyntaxError: Unexpected token < in JSON at position 43 at JSON.parse (<anonymous>) at XMLHttpRequest.xhr.onload (create:150)
output/response from json_encode
Code: {"location":"..\/public\/blog_img\/8.png"}
I hope someone can help me..
This is me. JK not me.
-
falcon812311 I can use google
 
-
Posts: 26
Threads: 13
Joined: Sep 2016
Reputation:
0
(08-27-2020, 05:09 AM)InsiteFX Wrote: Code: xhr.open('POST', '<?= base_url('admin/blog/imgUpload') ?>');
// change to
xhr.open('POST', "<?= base_url('admin/blog/imgUpload') ?>");
Thank you for reply, still not working. Chrome console show error
Code: Uncaught SyntaxError: Unexpected token < in JSON at position 43
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onload
This is me. JK not me.
-
InsiteFX Super Moderator
     
-
Posts: 6,727
Threads: 344
Joined: Oct 2014
Reputation:
246
at JSON.parse (<anonymous>) looks to me like it is from one of your headers.
I would do a single step debug on the code or do var_dumps here and there,
to see if something is wrong.
What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
-
anturom Newbie

-
Posts: 6
Threads: 1
Joined: Mar 2019
Reputation:
0
08-27-2020, 02:10 PM
(This post was last modified: 08-27-2020, 02:22 PM by anturom.)
By looking at your code, most probably the image location returned in the JSON object does not exist, because you are building it from $imageFolder, which uses a relative path.
To the point, instead of this
PHP Code: $img = [ 'location' => $filetowrite ];
try to use this:
PHP Code: $img = [ 'location' => base_url('public/blog_img/') . $temp['name'] ];
If it still does not work, consider installing Fiddler (or some equivalent HTTP traffic monitoring tool) to debug what's going on. This will let you see the exact HTTP response that gets returned.
-
argaLion Newbie

-
Posts: 1
Threads: 0
Joined: Jul 2022
Reputation:
0
07-13-2022, 04:46 PM
(This post was last modified: 07-13-2022, 04:52 PM by argaLion.)
I have tried this, this is my solution and i've tried it and it's working
first of all, change the CI_ENVIRONMENT into production. in development, xhr.responseText in the script will not just return the new location from json of the uploaded image but also returned the whole script for debugging in development environment. it's disrupting the plugin to convert the new location into the output format
then, i also take autorom advice with a little improvement from me,
in the Controller, change this line
PHP Code: $img = [ location' => $filetowrite ];
into
PHP Code: $img = [ location' => base_url('/assets/img') . '/' . $temp['name'] ];
lastly for the script in the view
i slightly change this line
PHP Code: document_base_url: '<?= base_url() ?>',
to this
PHP Code: document_base_url: "<?= base_url('admin'); ?>",
the reason is because my url of my view for the text editor is
http://localhost:8080/admin/manage-beranda
somehow it keeps convert the image url into http://localhost:8080/admin/my_image_name.jpg
while the actual url is http://localhost:8080/assets/img/my_image_name.jpg
note: my image folder is inside public/assets/img/
sorry if i can't explain it well, i'm new to this whole concept of sharing about experience in code, i post this reply a few minutes after i registered my account.
|