22

I want to convert an image to base 64 with Laravel. I get the image from a form . I tried this in my controller:

public function newEvent(Request $request){
    $parametre =$request->all();

    if ($request->hasFile('image')) {
        if($request->file('image')->isValid()) {
            try {
                $file = $request->file('image');
                $image = base64_encode($file);
                echo $image;


            } catch (FileNotFoundException $e) {
                echo "catch";

            }
        }
    }

I get this only:

L3RtcC9waHBya0NqQlQ=

12
  • 2
    $request->file() doesn't return the actual file content but an instance of UploadedFile. You need to load the actual file to convert it. Try: $image = base64_encode(file_get_contents($request->file('image')->path())); Commented Sep 13, 2017 at 21:22
  • please to make the inverse operation? base64 to image Commented Sep 13, 2017 at 21:35
  • base64_decode($image)? Did the first comment help you? Commented Sep 13, 2017 at 21:36
  • for the first i think this work base64_encode(file_get_contents($request->file('image'))); Commented Sep 13, 2017 at 21:39
  • now i want to decode and save but this dont work file(base64_decode($image))->move("images", $name); Commented Sep 13, 2017 at 21:40

4 Answers 4

46

Laravel's $request->file() doesn't return the actual file content. It returns an instance of the UploadedFile-class.

You need to load the actual file to be able to convert it:

$image = base64_encode(file_get_contents($request->file('image')->pat‌​h()));
Sign up to request clarification or add additional context in comments.

2 Comments

what is the purpose of this one? I just want to know I am little bit confused why you need to convert it?
@Biax20 they might want to store it in the database as a string, just as one example
27

It worked for me in the following way:

$image = base64_encode(file_get_contents($request->file('image')));

I eliminated this part ->pat‌​h();

1 Comment

When I tried this, I got this error : "file_get_contents(): Filename cannot be empty".
3

Don't forget to append file type.

Example for pdf :

$file = "data:@file/pdf;base64,".base64_encode(file_get_contents($request->file('image')));

Example for image :

$file = "data:image/png;base64,".base64_encode(file_get_contents($request->file('image')));

Comments

0
//html code
<input type="file" name="EmployeeImage">

//laravel controller or PHP code
$file = $request->file('EmployeeImage');
$image = base64_encode(file_get_contents($file)); 

// display base64 image
echo '<img src="data:image/png;base64,' . $image . '" />'; exit();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.