Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ankitsoni's avatar

How to Upload File/Image Directly In database not directory Storage

I wanna upload image in the database directly can some please tell me how i done this ....

0 likes
26 replies
tealiedie's avatar

convert your image into blob before saving it to database.

samo's avatar

You could use Intervention Image to do this stuff

$pic = new Picture;
$pic->data = (string) Image::make('public/bar.png')->encode('data-url');
$pic->save();
ankitsoni's avatar

@samo but this stores image in public directory not in database could you please tell me how to store it in table not disc directory

usama.ashraf's avatar

@ankitsoni try this:

$temp = file_get_contents($yourFile);
$blob = base64_encode($temp);
// Store $blob in the database just like any other field. The column type should be 'blob' ideally.
pmall's avatar

This is a bad idea to store images in database.

2 likes
samo's avatar

this doesn't store any kind of image, it encodes an given image into a data-url driven format

in laravel you are free to load the image from 'storage/pictures' instead of 'public/', thats a simple string

and of course as @pmall said, its a bad idea to store your image that way

ankitsoni's avatar

@pmall i know this is bad idea i used to store it in directory disc but now application that i want i needs to store it in database where size will be max 30kb

d3xt3r's avatar

@pmall Apart from increase in query time, any other justification for it being bad ?

1 like
phpMick's avatar

I just do this:


  $file = file_get_contents($tmpFileName);

    //if the item does not have a drawing - add one
    if ($item->drawing === null) {
      $drawing = New Drawing();
      $drawing->bitmap = $file;
      $item->drawing()->save($drawing);
    }else{
      //if the item already has a drawing, just update it
      $item->drawing->update(['bitmap' => $file]);
    }


My images are 6kb, so I figure that this is the best place for them. They will also get backed up with my DB.

Mick

ankitsoni's avatar

@phpMick i tried your way but it didn't work for me.. Could some one please tell me how i simply upload image in database and retrieve it back to show page i currently use like this but it didn't work

ankitsoni's avatar
Public function store(){
$vle = new Vle($request->all());
$vle->save();
if($request->hasFile('thumbnail'))
    {
        $data = file_get_contents(Input::file('thumbnail')->getRealPath());
        DB::table('vles')->insert(array(
                'thumbnail'=> $data
            )
        );
    }
ankitsoni's avatar

@enkay as you said i decode the image into base 64 by using

if ($request->hasFile('thumbnail')) { $data = file_get_contents(Input::file('thumbnail')->getRealPath()); $base64 = base64_encode($data); } // now don't understand the logic how to retrieve it as like file ???

enkay's avatar

@ankitsoni Click the second link I posted. You don't need to decode the base64 blob, you can use it directly in your img tag.

phpMick's avatar

@ankitsoni what happened when you try my code? Works for me.

Here is how I retrieve the images:

 if($item){
      $drawing = $item->drawing;
      $arrResponse['success']='true';
      if($drawing){
        $arrResponse['bitmap']=base64_encode($drawing->bitmap);
      }
    }

I am using AJAX.

Mick

ankitsoni's avatar

@phpMick decoding is not working is there any simple method to retrieve it ???

i check to encode myfile online it shows correct encoding but how i decode and retrieve it to show.

link that you post is not works for me is there any simple method to get it ???

TuxyQ's avatar

@d3xt3r one good reason not to: you are invoking php to serve something your filesystem and webserver are generally a lot faster at serving(nginx for example is among the fastest to serve static files).

That said, storing files in the database isn't the worst thing you can do, but you should know the impact it may have, especially if you have a site of some size.

EmilMoe's avatar

I believe you can store binary (BLOB) in databases, which is basically storing an image in the database without converting to some string.

I would avoid it too, but I think it's possible.

ankitsoni's avatar

@EmilMoe yes i'm using blob and convert the image into base64_encode to save it but prob is to show the image how i retrive it whereas i decode it before it to show but still it not working

EmilMoe's avatar

Just use file_get_contents()

'INSERT INTO table(image) VALUES("'. file_get_contents($imagepath) .'")';
phpMick's avatar

This is how I display it:

 $('#thumbnail').attr('src','data:image/bmp;base64,' + data.bitmap);

Again using AJAX and JQuery.

Mick

lucasfranson's avatar

I know that probably you solved your doubt, but I was looking for something similar and I didn't find it, so I will leave the following code for someone that may need it. The goal of this code is to get an image from Pixabay using an URL.

My solution for something similar:

public function store(){       
    $url = json_decode(request('photo')); //Photo is the field that I fill in the view, that contain a URL to my image in pixabay;
    $contents = file_get_contents($url);
    $name = substr($url, strrpos($url, '/') + 1);
    $blob =  base64_encode($this->resizeImage($contents));
    Photos::firstOrCreate(['photo' => $name,'thumb' => $blob]); //Photos is my model
}      

private function resizeImage($contents) : string {
    return (string) Image::make($contents)->resize(75, 75)->encode('data-url');  // Very important this cast to String, without it you can not save correctly the binary in your DB;   
}

View: For use the code in my view I put: When I return to view the Model I use a 'for' to print all images, like that:

@foreach($photos as $element)
    <img src="{{ base64_decode($element->thumb) }}" alt="" >
@endforeach

#Warning Is very important you have a Blob field in your DB, so in your Schema on Laravel Migrate you have to put something as: $table->binary('thumb');

You can check my code on my git: lucasfranson10/multisafepay

Tray2's avatar

Try avoid storing binaries in you database as long as possible. It will slow the database down and every query you write you will need to specify that the image shouldn't be loaded.

Use the filesystem for binaries.

Please or to participate in this conversation.