Image Upload Not Working (Froala Editor) - javascript

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.

Related

Jquery & Ajax -> File upload not possible

I got totally lost.
Ive tried to make some Image Upload function in PHP and everything works fine. Because i dont want the whole Page to reload, when uploading a File i wanted to use AJAX with Jquery, to send the Form Content (Image) via POST to a file like upload.php with an hidden ajax request.
No matter what i try its impossible to send anything with formData(). I copied & pasted several Sample Codes, tried changing the Code, nothing happens when i use formData().
A normal request with Jquery / Ajax, using POST works fine.
Here ist the Sample of my last used Code..
Could my XamPP has been misconfigured, or what could cause that really not one of the Scripts from google, tutorial pages etc works?
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
<button id="Knopf">Knopf</button>
<div id="Disp">fghfgh</div>
</body>
<script>
$(document).ready(function(){
$("#Knopf").click(function(){
var formData = new FormData(Test);
$.ajax({
url : "uploadtest2.php",
type : "POST",
data : formData,
cache : false,
contentType : false,
processType : false,
success : function() {
$("#Disp").html(result);
}
});
});
});
</script>
</html>
<?php
$target_dir = "Media/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The problem is this:
if(isset($_POST["submit"])) {
There's no element named submit in the form, so this check fails. Even if you had a submit button in the form, it wouldn't be included in formData, because buttons are only automatically included in POST data when they trigger normal form submission.
You can add that to formData.
var formData = new FormData(Test);
formData.set("submit", "1");
Or you could change your test to
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
Please see: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
You must use a Form Element:
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
Consider the following example.
$(function() {
$("#Test").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "uploadtest2.php",
type: "POST",
data: formData,
cache: false,
contentType: false,
processType: false,
success: function(result) {
$("#Disp").html(result);
}
});
});
$("#Knopf").click(function() {
$("#Test").submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" />
</form>
<button id="Knopf" type="submit">Knopf</button>
<div id="Disp">fghfgh</div>
It is better to bind to the submit callback. This way, if the User submits the form or clicks Submit, the callback is triggered. We need to .preventDefault() on the Event to ensure the Form doesn't post or submit the data. Now we can then perform the AJAX call without the page being refreshed.
In your success callback, you must pass in a variable to be used for the returned data. Otherwise result will be undefined.
With the proper FormData, there should be no issue uploading. this in the callback refers to the Form Element itself.
Consider updating your PHP as well:
if(isset($_POST["submit"])) {
Change this to:
if(isset($_POST["fileToUpload"])) {

How do I upload an image using PHP? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How do I upload an image and store it into a cookie? I want to be able to upload an image with limitations on e.g. file size restrictions.
Here is my PHP code:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
In this code is the function to upload a file with restrictions on.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<link href="bitnami.css" media="all" rel="Stylesheet" type="text/css" />
<link href="test.php"/>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
You have multiple faults in your logic.
1) You never check if an upload was actually performed. You just start working on the ['tmp_name'] without ever checking if it actually exists. Your FIRST action on processing an upload must be to check for errors:
if ($_FILES["fileToUpload"]['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileToUpload']['error']);
}
2) You're checking file types based on filename extensions. Nothing says a user can't do ren nastyvirus.exe cutekittens.jpg and get through your filename check. You're already using getimagesize() later on, so the extension check is pointless:
$info = getimagesize($_FILES['fileToUpload']['tmp_name']);
if ($info === false) {
die("Not an image at all");
}
if (($info[2] != IMGTYPE_GIF) && ($info[2] != IMGTYPE_JPG) && ($info[2] != IMGTYPE_PNG)) {
die("Not a gif/jpg/png");
}
if (($info[0] > $maximum_width) || ($info[1] > $maximum_height)) {
die("Too tall/wide");
}
And then, after all that - why store it in a cookie? Cookies are naturally limited in the maximum amount of data that can be stored. You shouldn't exect to be able to store more than a couple kilobytes at most. Since you've set your upload size limit at 500k, you WILL end up with corrupted/truncated images if you do store a 500k into that 1-2k cookie.

Can't Upload Image from froala editor

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.

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