Home > Software engineering >  Symfony - Store images incoming from requests
Symfony - Store images incoming from requests

Time:06-30

I am making an app with a feature of adding posts. Every post have the possibility to contain an image. My main problem is the thing I don't know how to store the images. I know I can create a seperate folder named for example "private" but the thing is it should have some structure to not put all images together. I would like to avoid having thousands of images in one folder. I've seen somewhere that people make a structure of folders then somehow decide where each image should be stored (for example by original file name). This looks something like this:

private:
    15:
       23:
          image_file.jpg
       88:
          image_file2.jpg
    13:
       48:
          image_file3.jpg

Is there a way to do this kind of file structure in Symfony? The only solution that I have in my mind is somehow transforming filenames into numbers then using modulo. But I don't think it is a good idea.

CodePudding user response:

Simply incorporate your Post ID into path:

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Entity\Post;

class ArticleAdminController extends BaseController
{
    public function temporaryUploadAction(Request $request, Post $post, string $projectDir)
    {
        /** @var UploadedFile $uploadedFile */
        $uploadedFile = $request->files->get('image');
        $uploadedFile->move("{$projectDir}/private/{$post->getId()}");
    }
}
  • Related