Can't Upload Image from froala editor - javascript

I'm using XAMPP as the server and well i can't seem to upload the image like the documentation of the editor showed me... here is the link:
http://editor.froala.com/server-integrations/php-image-upload
I already investigated about the problem and normaly they all say is the link that's not correct because you need to put the absolute url there , but even that doesn't seem to work.
Here is the code:
JS
$(document).ready(function(){
$('textarea').editable({inlineMode: false, height:200, imageUploadURL: 'upload_image.php', imageErrorCallback: function (data) {
// Bad link.
console.log(data);
}
});
});
upload_image.php:
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], "C:\ xampp\htdocs\Swaggy\img\ " . $name);
// Generate response.
$response = new StdClass;
$response->link = "/swaggy/img/" . $name;
echo stripslashes(json_encode($response));
}
When i try to upload an image he forms an img tag in the editor in base 64 and then dissapears. The debugger shows me that the file upload_image.php has a 200 status and the error that shows me from console is this :
Object {code: 4, message: "Parsing response failed"}

It looks there is a problem with the PHP from your server and the response can't be parsed. You should check with Firebug what is the response from the server when you try to upload an image. finfo_file function for instance is available only starting with PHP 5.3. If your version is older this is the problem most probably.

Related

Return error from php to dropzone.js

I would like to return an error on a case from my php code that handles the upload.
Currently if the php upload fails the JS still thinks it successes which I presume is to do with the fact it returned fine.
I have tried returning false instead of a string but that still runs the this.on('success') function.
PHP
public function imageUpload(){
//Сheck that we have a file
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
($_FILES["file"]["size"] < 3500000)) {
//Determine the path to which we want to save this file
$newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
}
JS
$(document).ready(function(){
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone('div#imagesdropzone', { url: '/admin/imageUpload',
parallelUploads: 100,
maxFiles: 100,});
});
Dropzone.options.imagesdropzone = {
init: function() {
this.on('success', function( file, resp ){
console.log( file );
console.log( resp );
});
this.on('error', function( e ){
console.log('erors and stuff');
console.log( e );
});
}
};
Yes, its right. You have to set an HTTP Header.
Have a look at:
https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-an-error-returned-by-the-server
If you have an HTTP Error and want to show it in the hover error message of DropzoneJS you can:
myDropzone.on("error", function(file, message, xhr) {
var header = xhr.status+": "+xhr.statusText;
$(file.previewElement).find('.dz-error-message').text(header);
});
(You need jQuery for that code [$().find();])
The other way would be to return a JSON error message via PHP:
//define text for error message
$output['error'] = 'No Token';
//return right HTTP code
if( $error ){
http_response_code (401);
}
else{
http_response_code (200);
}
//set Content-Type to JSON
header( 'Content-Type: application/json; charset=utf-8' );
//echo error message as JSON
echo json_encode( $output );
Where does this.on('success') take the information about the success/failure of the (internal) PHP upload process?
I guess from the HTTP header's status code, which is 200 (OK) even if the upload failed (it just prints some error text).
I recommend you to set a 500 header if the upload fails.
Use below php code snippet
public function imageUpload(){
//Сheck that we have a file
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
($_FILES["file"]["size"] < 3500000)) {
//Determine the path to which we want to save this file
$newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
header('Error: A problem occurred during file upload!', true, 500);
//echo "Error: A problem occurred during file upload!";
}
} else {
header("Error: File ".$_FILES["file"]["name"]." already exists", true, 500);
//echo "Error: File ".$_FILES["file"]["name"]." already exists";
}
} else {
header("Error: Only .jpg images under 350Kb are accepted for upload", true, 500);
//echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
header("Error: No file uploaded", true, 500);
//echo "Error: No file uploaded";
}
}

Image Upload Not Working (Froala Editor)

I have read the Froala Help Docs over 10 times now. I still can't get it to work :(
When I click the upload icon in my editor and select an image to upload, nothing happens. The dialog box that asks you to choose an image pops up, and after selecting the image, it dismisses but nothing happens on the page afterwards.
It's definitely something wrong with my code. However, I can't figure out what it is.
My view page:
<textarea id="edit" name="message"> </textarea>
My js:
$(function() {
$('#edit').editable({
height: 400,
imageUploadURL: '/assets/upload_image.php',
imageUploadParams: {id: "edit"},
imageUploadParams: {id: "edit"},
placeholder: "Write something...",
inlineMode: false
})
});
My upload_image.php file:
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "http://localhost/assets/uploads/" . $name);
// Generate response.
$response = new StdClass;
$response->link = "http://localhost/assets/uploads/" . $name;
echo stripslashes(json_encode($response));
}
What I have tried to fix this issue:
In upload_image.php, I have replaced the upload folder path (original: http://localhost/assets/uploads/ to just uploads and created an uploads folder in that directory. Still no luck.
I have tried placing all the files together in the same folder but no luck.
Any help is highly appreciated.
I have gone through the same issue and I am sharing working code for you.
index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/froala_editor.css">
<style>
body {
text-align: center;
}
div#editor {
width: 81%;
margin: auto;
text-align: left;
}
</style>
</head>
<body>
<div id="editor">
<form method="post">
<textarea id='edit' name='edit' style="margin-top: 30px;" placeholder="Type some text">
<h1>Textarea</h1>
<p>The editor can also be initialized on a textarea.</p>
</textarea>
<input name="submit" type="submit">
</form>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/froala_editor.min.js"></script>
<script type="text/javascript" src="js/plugins/image.min.js"></script>
<script>
$(function() {
$('#edit').froalaEditor({
height: 300
})
});
</script>
</body>
</html>
upload_image.php
<?php
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png");
// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);
// Get extension.
$extension = end($temp);
// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);
/* if you want to check extension of a file, then please remove the below if condition */
/*if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {*/
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
// Save file in the uploads folder.
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/uploads/" . $name);
// Generate response.
$response = new StdClass;
$response->link = "http://localhost/test/editor-3/html/uploads/" . $name;
echo stripslashes(json_encode($response));
//}
?>
Now Open included javascript file image.min.js and just find and change the imageUploadURL parameter to url of your upload_image.php file, in my case, it is:
imageUploadURL: "http://localhost/test/editor-3/html/upload_image.php",
I am going to add an answer here because for one Froala's documentation is terrible. I had experienced multiple issues with both image and file uploads and spent many hours going crazy till after a few weeks I finally figured out the issue and hope this can help someone else.
First
fileAllowedTypes: ['*']
documentation
The following Froala specifies that this option will allow any file type to be uploaded...wrong. The thing that Froala is not telling you is that in order to be able to upload any file type you have to specify the extension of the file as well as the MIME-type. If you don't reguardless of this option it will not work. It will only allow PDF and TXT.
What to do
When you download the Froala SDK you need to head over to
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/File.php //for File upload
and
wysiwyg-editor-php-sdk-master/lib/FroalaEditor/Image.php //for Image upload
In those files you will see something like
'allowedExts' => array('zip', 'txt', 'pdf'),
'allowedMimeTypes' => array(
'text/plain',
'application/pdf',
'application/zip'
)
This is where you need to add your extensions and MIME-types that you want to allow. You must specify both the extension and MIME-type of the file.
If you are having trouble finding the MIME-type of a particular file just use this site.
I am guessing that this might apply to other languages as well or at least be a similar solution but I can confirm this for php
Hope this helps someone out in the future.

PHP redirect after form processing

I've been staring at code too long however when I used a simple script to save a form with:
endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>
at the end the page redirected back to itself just fine, however now I have a longer script here I can't quite figure out where or how to code my redirect:
<?php
session_start();
$directory = 'users/'.$_SESSION['username'].'/';
//here you can even check if user selected 'Delete' option:
if($_POST['Action'] == "DELETE"){
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete))
echo $file_to_delete." deleted.";
else
echo "Error deleting file ".$file_to_delete;
}
if($_POST['Action'] == "SAVE"){
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
}
?>
may be you should use querystring variable while redirecting.
if($_POST['Action'] == "DELETE") {
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete)) {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
} else {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0& file='.$file_to_delete);
}
}
In codesaveindex.php:
if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
echo "Error deleting file ".$file_to_delete;
}
You can't redirect if the page after html has been outputted.
You need to either use output buffering or redirect using javascript,
or organise it so that the redirect happens before the html is shown.
i have a class written for such thing, should be very easy to use class.route.php
simply do this where you want to redirect: route::redirect('page', http_status);

How to send image from main page to another?

I have been searching for this answer for days and cannot come across an answer. Maybe because i do not understand them and can not apply them to what i am trying to do.
i am using php to save images on the server when the user presses submit and when that happens, i would like the image to appear on the next page in the image src. As you can see that the name of my next page is random but similar to my image name aside from the extensions. So i was wondering if that would play a part in helping me do something? as at the end of my php i go straight to the random stringed page that was created.
function findexts ($filename) {
$filename = $_FILES["file"]["name"];
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
if(isset($_POST['submit'])){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 3000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = findexts ($_FILES['file']['name']) ;
$newName = generateRandomString();
$fileName=$newName.".".$ext;
while (is_file("upload/" . $fileName)){
$newName = generateRandomString();
$fileName=$newName.".".$ext;
}
$target = "upload/";
move_uploaded_file($_FILES["file"]["tmp_name"],
$target . $fileName);
$newfile = fopen("img/" . $newName.".html", "w") or die("Unable to open file!");
$newImgWeb = $newName.".html";
copy("img/template.html","img/" . $newImgWeb);
fclose($newfile);
header("Location: img/$newImgWeb");
}
} else {
//echo "Invalid File"
}
} else {
}
this is my php and i don't know how i would go about doing it?
my html and php are seperate too, but are linked under the form action="upload_file.php"
<img src="../upload/<?php echo $fileName ?>">
but i'm just getting a bunch of errors, i have no clue on what i should do next. I'm just a beginner and learning a lot through doing this.
Also, i tried doing this in javascript where i would take the url of the current webpage, remove the begining url and leave with the end. So it would be like "adSEvF3A.html" then i removed the ".html" part and from there i couldn't identify which extensions to look for .png .jpg etc. so i couldn't do document.getElementById('image').src=newImg;
Thanks in advance!
I had realised that i needed to put
session_start();
at the begining of the php file that i want to obtain the variable from. When i was working with session_start(); i had done it all wrong, and thought that $_SESSION had to always be declared right below session_start(); i know many of you will think it's stupid to think that. But hey, at least i figured it out.
test1.php
session_start();
$var = "hello.jpg";
$_SESSION['image'] = $var;
the variable that i wanted to declare needed to be above the $_SESSION so that it can be stored inside it.
index.html
<?php
include ('test1.php');
$image = $_SESSION['image'];
?>
<img src="upload/<?php echo $image ?>">
and then it worked.
Thanks CMKanode for helping me!

Multi-Step Form with File Upload

I have a multi-step form. What I want to achieve here is to allow user to upload a file (with some validation using jquery.validate plugin) and store the file to mySQL database.
Previously, I wasnt using multi-step form design (a one-page per step design instead) and therefore when user clicked the "submit" button, I would have if(isset($_POST['submit'])) and $_FILES to validate the file through PHP. Below is the PHP code that will be triggered when user clicked "submit" button .
if(isset($_POST['submit']))
{
$allowedExts = array("mov", "mp4", "mpeg", "wmv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "video/quicktime") || ($_FILES["file"]["type"] == "video/mp4") || ($_FILES["file"]["type"] == "video/mpeg") || ($_FILES["file"]["type"] == "video/x-ms-wmv")) && in_array($extension, $allowedExts) && (!empty($_POST["title"])) && (!empty($_POST["description"])))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// check if the file already exist in Uploaded folder
if (file_exists("uploaded/".$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"]." already exists. ";
}
else
{
echo "<br />".$_FILES["file"]["name"]." has been uploaded! <br /><br />";
echo "Upload: ".$_FILES["file"]["name"]."<br />";
echo "Type: ".$_FILES["file"]["type"]."<br />";
echo "Size: ".($_FILES["file"]["size"] / 1024)." kB<br />";
echo "Stored in: "."uploaded/".$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploaded/".$_FILES["file"]["name"]);
$name = $_FILES["file"]["name"];
$url = ""; //some URL
mysql_query("INSERT INTO video (name, title, description, url) VALUES ('$name', '$title', '$description', '$url')") or die(mysql_error());
}
}
}
else
{
if (!empty($_POST["description"]) && (!empty($_POST["title"])))
{
echo "Invalid file";
}
}
}
But now, since I have change my design to multi-step form, this logic seems not working anymore. This is my fiddle.
I was thinking to change the "Upload" button type from type="button" to type="submit"so that I can use my old PHP logic to process the file and upload to database, however this causes my multi-step form to stop going to the next step.
Any brilliant ideas or suggestions?
If you want to avoid page reloads, you could try posting the form through a hidden iframe and then reading the response on load. As far as I know this should work in all browsers
<iframe name="target_iframe">..</iframe>
<form target="target_iframe">..</form>
Check out How do you post to an iframe?
If you're happy dropping support for older browsers you can post files using ajax. Maybe check out using html5 for file upload with ajax and jquery

Categories

Resources