Redactor image upload not working on laravel 5 - php

Same code working in laravel 4 but not working in laravel 5.
Here is all codes :
//Redactor Image Upload
Route::post('image/upload', function(){
$image = Input::file('file');
$filename = 'bdtimes'.rand(10, 99999999).'.'.$image->getClientOriginalExtension();
$move = Image::make($image->getRealPath())->save('uploads/images/original/'.$filename);
if($move){
return Response::json(['filelink'=>'/uploads/images/original/'. $filename]);
}else{
return Response::json(['error'=>true]);
}
});
Redactor Script :
$(function()
{
$('#redactor').redactor({
focus: true,
imageUpload: '{{ url() }}/image/upload',
imageManagerJson: '{{ url() }}/image.php',
plugins: ['table', 'video','imagemanager','fontcolor','fontsize','fullscreen'],
maxHeight: 300,
minHeight: 300
});
});
In Chrome Developer Tool this error showing when i try to upload image.
Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:8000/image/upload
What is problem ? Please help me .
Thanks

Updated Answer
There is a problem with the token. Change the Redactor script..
$(function()
{
$('#redactor').redactor({
focus: true,
imageUpload: '{{ url() }}/image/upload?_token=' + '{{ csrf_token() }}',
imageManagerJson: '{{ url() }}/image.php',
plugins: ['table', 'video','imagemanager','fontcolor','fontsize','fullscreen'],
maxHeight: 300,
minHeight: 300
});
});

This means that some line in your route is having an error. Looking at your code I do not see any obvious issue, it could be related to import etc what is not shown here.
Try using dd() after every line to print debugging info until you locate exact line what is broken.
You can also look at the ajax request response from Chrome Developer Tool as it must have more info about the exact error.

I had the same problem when using redactor with yii framework. I think the problem is with setting the route to the upload directory. So the developers of redactor changed some code to prevent this.
In RedactorModule.php > public function getSaveDir() change this:
$path = Yii::getAlias($this->uploadDir);
if (!file_exists($path)) {
throw new InvalidConfigException('Invalid config $uploadDir');
}
if (FileHelper::createDirectory($path . DIRECTORY_SEPARATOR . $this->getOwnerPath(), 0777)) {
return $path . DIRECTORY_SEPARATOR . $this->getOwnerPath();
to this:
$path = Yii::getAlias($this->uploadDir) . DIRECTORY_SEPARATOR . $this->getOwnerPath();
if(!file_exists($path)){
if (!FileHelper::createDirectory($path, 0775,$recursive = true )) {
throw new InvalidConfigException('$uploadDir does not exist and default path creation failed');
}
}
return $path;

Related

Summernote upload image not showing in the editor after submitting to update

I have been working on a project, using Summernote. My project is like a blog system and I need to upload contents and images.
I have checked the other posts here and other places and managed to insert images to the file with ajax where I want to save the images. However, when I am editing, an image is there but once I click "update button" (submit button in a form), the images won't be there anymore.
I also check the inspect and resource says
Request URL: http://localhost/cms/admin/includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG
This is the right path but after updating, I get a message like
Request URL: http://localhost/%22includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG/%22
Also status code says
Status Code: 403 Forbidden
Here is my code
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
for(let i=0; i < files.length; i++) {
$.upload(files[i]);
}
}
},
height: 300,
});
$.upload = function (file) {
let out = new FormData();
out.append('file', file, file.name);
$.ajax({
method: 'POST',
url: './includes/editor-upload.php',
contentType: false,
cache: false,
processData: false,
data: out,
success: function(url) {
$('#summernote').summernote("insertImage", url, 'filename');
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(textStatus + " " + errorThrown);
}
});
};
And this is my php code (editor-upload.php)
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'images/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'includes/images/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Insert uploaded image to summernote editor
Summernote image upload
Summernote 0.8.12 Image Upload And Delete
I have tried these but nothing worked for me.
I have of course Summernote js and css file and am using Summernote 0.8.18
I am sure I am doing something wrong but I can't figure this out yet.
I am hoping somebody can help me out.
If the images folder is inside of the includes folder, change the following line:
$destination = 'images/' . $filename;
to
$destination = './includes/images/' . $filename;
Next, enter the full URL name and the full path to the image instead of
echo 'includes/images/' . $filename;
Also, the editor-upload.php file in your Ajax upload script may be causing the 403 errors. if the upload file is not in the same folder as your form and index.php page, it can prove problematic.
Try moving the file to the same folder as your form with the summer note editor, and enter the file in your Ajax script as
'editor-upload.php'

cant preview image with ajax in MVC project

i am making a blogsite, and i can upload images to it using tinymce's richtext-editor, but the preview of the image doesnt show up in the textarea. (although if i upload the image anyway, i can perfectly see it in the blogfeed).
i suspect there is a problem with how i implemented tinymce into the MVC framework (brad traversy's framework on udemy). because when i look at the filepaths to the image they are different.
"<img src="http//localhost/mywebsite/content/images/image.jpg>". (image from the blogfeed)
"<img src="http//localhost/mywebsite/posts/content/images/image.jpg". (image from the tinymce editor)
for some reason the controller is being included when the image is loaded into the tinymce editor. i tried messing around with where the images should be saved, if i set it to $imageFolder = "images/"; then i can get the images to be seen in the blogfeed but not the preview. if i set $imageFolder = "../images/"; then the image can be seen in the preview but not in the blogfeed.
i also tried to define a constant path, "define ("IMGROOT", /path/to/my/site)" and then setting $imageFolder = IMGROOT . 'content/images"; but then i got the error "not allowed to load local resource" and im not very keen to circumvent that since it is probably a good reason to not load local resources once my blog is published.
upload.php:
<?php
//upload images
header('Content-Type: application/json');
/***************************************************
* Only these origins are allowed to upload images *
***************************************************/
$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com");
/*********************************************
* Change this line to set the upload folder *
*********************************************/
$imageFolder = "images/";
$temp = current($_FILES);
// 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'}
echo json_encode(array('location' => $filetowrite));
upload_handler:
tinymce.init({
selector: '#tinymcebody',
plugins: "image",
images_upload_url: '<?php echo URLROOT;?>/upload.php',
images_upload_handler: function (blobInfo, success, failure) {
var xhr;
var formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '<?php echo URLROOT;?>/upload.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Ereror: ' + 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());
console.log(formData);
xhr.send(formData);
}
});
I fixed it by adding a base_url to the tinymce init. this way it ignores the routing i got from the MVC tutorial and just loads any pictures that are in the specified folder. i also added 3 lines, im not entirely sure yet what they do but they do something to the path of the file.
note that i have defined constants in a config.php folder, so "URLROOT" is defined as "http:localhost/mywebsite".
tinymce.init({
selector: '#tinymcebody',
plugins: "image",
document_base_url : "<?php echo URLROOT; ?>",
relative_urls : false,
remove_script_host : false,
convert_urls : false,
images_upload_url: '<?php echo URLROOT;?>/upload.php',
images_upload_handler: function (blobInfo, success, failure) {
var xhr;
var formData;

how to debug a php post script on the server and see echo output

newbie question. I have a web page sending $_POST data to a php script on a server.
How to debug php (see the output of echo) ?
If I just browse to the www.serveradress.com/myscript.php,I see nothing...
I am using Chrome.
Thanks
Edit: I am using ngFileUpload on the client side.
Edit: I see that the file is well received because I see it on the server with filezilla.
client side:
$scope.uploadBoardPic = function(file, errFiles) {
$scope.boardPic = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: 'http://myserver.com/angular-seed/appendBoardPicture.php',
method: 'POST',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}
server side:
<?php
$filename = $_FILES['file']['name'];
$destination = './' . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
echo "<pre>" . print_r($_FILES, true) . "</pre>";
?>
Php keeps POST variables within the $_POST global. You should be able to run something to the affect of
echo "<pre>" . print_r($_POST, true) . "</pre>";
To get back the debugging information you need. This of course will only work if you are doing a valid POST via a form. That meaning that the page is actually going to change. Looking at your question though, it looks like you are working in all javascript for your post/reply. In that case, you will want to look for the reply information from php, within your javascript. You can do this by looking at the network tab, during the submission.
As a good practice, you should use error logs for this kind of task. If you have not set up a error log then you should set it up in the apache config file.
Once you set the error log simply type this:
error_log(var_export($_POST, true));
and you can see the exports in your error log.
http://php.net/manual/en/function.error-log.php

Codeigniter : Multiple File Uploading

I tried many multiple file uploaders which can be integrated with codeigniter like
pulpload
jquery file upload
Even though they work perfectly in the pure php environment, i could not make them work in codeigniter framework. I tried this for two days.. tried many articles which was in the github and blogs..
But i could not made it in codeigniter framework..
If anyone can tell me it by step by step or if there is a tutorial for that, please help me.
I am a newbi to codeigniter..
New:
I downloaded the blueimp Jquery-File-Upload plugin, and followed this link as it is..
https://github.com/blueimp/jQuery-File-Upload/wiki/Latest-jQuery-File-Upload-easy-integration-with-codeigniter
When I select a file and click upload in chrome it says:
Error SyntaxError: Unexpected token <
In firefox it says:
Error SyntaxError: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I examined the difference between using it on my server and on the demo server, on my server in firebug the POST return is the entire index.html...
but on the demo server it returns JSON data..
Here is the modified section of js/main.js that I changed:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'upload/do_upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
The only thing I changed was making index.html to have the form action point to my script (upload/do_upload)
controller
function add()
{
if(isset($_POST['submit']))
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'
.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table_name',$data);
$this->session->set_flashdata('message','<div class="alert alert-success">Record has been successfully saved.</div>');
}
}

JQuery File Upload Custom Path Problems

I am using JQuery File Upload plugin to make add the possibility to upload files to my website.
The upload script is in a page like "index.php?cartella_id=x" (x is a number that indicated a album ID).
I would like to store files like this:
server/php/files
- directory 1/
- - Image x
- - Image y
- directory 2/
- - Image z
- - Image z(2)
I basically want to create a different directory for each album.
Storing the images like I want is not hard because I pass $cartella_id by using a hidden input in the form like this
<input type="hidden" name="cartella_id" value="<?php echo $cartella_id; ?>">
In the server/php/index.php file I check if the user is logged in and if the album exists like this
session_start();
if(!isset($_SESSION["username"])) {
die();
}
if(isset($_REQUEST["cartella_id"])) {
$cartella_id = (int) $_REQUEST["cartella_id"];
$sql = "SELECT * FROM cartelle WHERE cartella_id = $cartella_id";
$query = mysql_query($sql);
if($cartella = mysql_fetch_array($query)) {
$upload_dir = '/files/'.$cartella_id.'/';
} else {
die();
}
} else {
die();
}
And in the UploadHandler.php page I edit the 'upload_dir' and 'upload_url' options.
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/'.$_REQUEST["cartella_id"].'/',
'upload_url' => $this->get_full_url().'/files/'.$_REQUEST["cartella_id"].'/',
Upload works fine... the problem is that if I refresh the upload page I can't see already-uploaded files like the script would show me when no custom path is specified. I can use $_SESSION to fix this problem but I don't like this solution and the Delete buttons wouldn't work in any case.
I studied the PHP code a lot and I've also googled a lot but I couldn't find a solution that works for me.
How do I send custom variables when the script is checking for existing files (I couldn't find that piece of code)?
How do I make the Delete buttons work?
Thanks in advance
So I solved the first problem (make files visible even after reloading the page) by editing js/main.js.
I edited this:
url: $('#fileupload').fileupload('option', 'url'),
to this
url: ($('#fileupload').fileupload('option', 'url') + "?cartella_id="+ document.getElementById('cartella_id').value),
Still have to make the delete buttons work though.
I had the same problem and i solved it enabling the user-directories and overriding the methods in the class UploadHandler as suggested here:
jQuery-File-Upload PHP-user-directories
I added an extra parameter to the delete url.
My index.php :
<?php
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function get_user_id() {
return $_REQUEST['recordId'];
}
protected function set_additional_file_properties($file) {
$file->deleteUrl = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.$this->get_singular_param_name()
.'='.rawurlencode($file->name)
.'&recordId='.$_REQUEST['recordId']
;
$file->deleteType = $this->options['delete_type'];
if ($file->deleteType !== 'DELETE') {
$file->deleteUrl .= '&_method=DELETE';
}
if ($this->options['access_control_allow_credentials']) {
$file->deleteWithCredentials = true;
}
}
}
$upload_handler = new CustomUploadHandler(array(
'user_dirs' => true,
));
and i changed the url in
my main.js:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/index.php?recordId=' + recordId,
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
});
}
i have not edited the UploadHandler.php

Categories