i wanna use tinyMCE editor for blog, but i have a problem with image uploading, so in my case i want to write the blog and also upload some images, but what if i don't have created an Article record in the database, then i can't attach uploaded images to the article record.
Yes i'm able to use base64 format for images, but this is not best practice to store whole base64 to the DB. I also don't want to allow upload image only if Article record is already created, so in editing mode.
I thought about that i can save these files to temporary folder and then while i will be storing the article i can use regex to match all images and attach these images to article and replace old img source, but i'm not sure if this approach is good.
Yes this is also option, but i don't like it too much, so instead i decided to upload images to temporary directory and after Article record is created i match all image sources and simply associate these files with new article record.
public function created(Article $article): void
{
$crawler = new Crawler($article->content);
// Get the src attribute of each `img` tag.
$imageSources = array_filter($crawler->filter('img')->each(function (Crawler $node) {
return $node->attr('src', '');
}));
foreach ($imageSources as $imageSource) {
$parsedSource = Str::of($imageSource)->after('tmp/')->toString();
$imagePath = Storage::disk('tmp')->path($parsedSource);
$imageFileName = pathinfo($imagePath, PATHINFO_FILENAME);
$imageExtension = pathinfo($imagePath, PATHINFO_EXTENSION);
// Add the media to the article's media collection.
$media = $article->addMedia($imagePath)
->setFileName("{$imageFileName}.{$imageExtension}")
->toMediaCollection('editor');
// Replace temporary image source with media URL.
$article->content = str_replace($imageSource, $media->getUrl(), (string) $article->content);
}
$article->saveQuietly();
}
@patressz only that you can only upload images for one user at once, and its a problem which can be solved in a lot less code.
Another approach I have used is to put a token in the user's session. When images are submitted, they are stored in a folder using that token as the foldername. When saving the blog get the images from the folder with the random token, or better still, use the folder long term as the image location.
@Snapey this is something that i have already solved. I have configured tmp disk and then while i storing the uploaded image i generate a foldername in combination with timestamp and random 20 char long string, so there's really a minimal chance that these two things match, but yes good to know another approach, thanks!
The endpoint returns a JSON response containing the location of the uploaded image, which will then be used as the source for that image in the content. This location value is embedded within the content attribute. Once the article is created, the entire content is processed to extract all image sources from it and after that i have all sources which i can use.