Prevent uploading file before form submit in richtext editors?

Viewed 44

I am trying to prevent from uploading image before form submit using summernote editor. The code I was using (jquery/ajax) worked well for uploading image, 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 submit button is clicked (until then, it should be there only as preview).

I use following code which is parsing base64 coded image from editor, decoding and uploading to server. it works fine when adding new article or updating article without adding new image into it.

Example : if article has 2 old images allready, and I add 1 more image then its trying to reupload that old images again, but old images are decoded so it doesn't upload them and inserting an undefined link into the editor.

I tried to validate with the server using :

if(file_exists($filename)){
  echo 'Already exist';
}

But had no luck to make it work.

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
  }   
  

Any help will be appricated! Thanks.

Solution :

I just needed to add if statement under foreach and take $submitted_text = $doc->saveHTML(); out of foreach, it works like a charm now.

if(preg_match('/data:image/', $srcStr)){}

if you want to add images to database, you can collect $filename to array $arr = array(); and implode or foreach in to database.

Can be used for all editors.

0 Answers
Related