Hi guys!
I am trying to prevent from uploading image before form submit using summernote richtext editor.
The code I was using (jquery/ajax) worked well for uploading image and saving text to database, but it was uploading image instantly when I add it to editor.
This was not desired behavior for me, 'couse if user add image to editor and then decide to close tab/close browser or go to another address, image will be stored on server - so I would like to upload image only when submitt button is clicked (until then, it should be there only as preview).
I use following code which is parsing encoded (base64) image from editor, decoding it and uploading to server.
it works fine when adding new article or updating article without adding new image in it.
Example : if article has 2 old images allready and I add 1 more image, then its trying to upload that old images again, but old images are decoded so it doesnt upload them and inserting a undefined link into the editor.
Here is my code :
if(strpos($submitted_content, '<img') !== false && strpos($submitted_content, ';base64') !== false) {
$doc = new DOMDocument();
$doc->loadHTML($submitted_content);
$tags = $doc->getElementsByTagName('img');
foreach($tags as $tag) {
// Get base64 encoded string
$srcStr = $tag->getAttribute('src');
$base64EncData = substr($srcStr, ($pos = strpos($srcStr, 'base64,')) !== false ? $pos + 7 : 0);
$base64EncData = substr($base64EncData, 0, -1);
// Get an image file
$img = base64_decode($base64EncData);
// Get file type
$dataInfo = explode(";", $srcStr)[0];
$fileExt = str_replace('data:image/', '', $dataInfo);
// Create a new filename for the image
$newImageName = str_replace(".", "", uniqid("img_", true));
$filename = $newImageName . '.' . $fileExt;
$file = '../uploads/large/' . $filename;
// Save the image to disk
$success = file_put_contents($file, $img);
$imgUrl = 'http://localhost/haber/uploads/large/' . $filename;
// Update the forum thread text with an img tag for the new image
$newImgTag = '<img src="' . $imgUrl . '" />';
$tag->setAttribute('src', $imgUrl);
$tag->setAttribute('data-original-filename', $tag->getAttribute('data-filename'));
$tag->removeAttribute('data-filename');
$submitted_text = $doc->saveHTML(); //This is the result of the editor to add database
}
Thanks for any help!