123ali's avatar

Images Upload and Saved into the database

I am using the laravel 6.0 and vue js I am try to upload and save image into the database but we are always getting this error.

Images Upload and Saved

<form @submit.prevent="imagesform" enctype="multipart/form-data" @keydown="errors.clear($event.target.images)">

Attach a picture

Submit

class Errors{ constructor(){ this.errors = {}; } get(field){ if (this.errors[field]) { return this.errors[field][0]; } } record(errors){ this.errors = errors.errors; } clear(field){ delete this.errors; } } export default { data(){ return{ showPreview: false, imagePreview: '', name:'', gander:'', errors: new Errors() } },
  methods:{
        imagesform: function(e) {
               e.preventDefault();
               alert('Hellow');
               let vueInstance = this;
               const config = {
                    headers: { 'content-type': 'multipart/form-data' }
                }
                let formData = new FormData();
                formData.append('images', this.imagePreview);
                axios.post('/company/public/saveimages', formData, config)
                .then(function (response) {
                    console.log(response);

                })
                .catch(function (error) {
                    console.log(error);
                    //currentObj.output = error;
                });
        },
        handleFileUpload(e){
            this.imagePreview = e.target.files[0];
            /*
            this.file = this.$refs.file.files[0];
            */
            let reader  = new FileReader();
            reader.addEventListener("load", function () {
            this.showPreview = true;
            this.imagePreview = reader.result;
            }.bind(this), false);
                if( this.imagePreview ){
                    if ( /\.(jpe?g|png|gif)$/i.test( this.imagePreview.name ) ) {
                        reader.readAsDataURL( this.imagePreview );
                    }
                }
        },
  },
    mounted() {
    }
}
public function saveimages(Request $request){

    $validator = Validator::make($request->all(), [
        'images' => 'required',
    ]);
        
    $data = $request->only(['images']);
    if(!empty($data['images'])){
        $imageName = time().'.'.$request->picture->getClientOriginalExtension();
        $request['images'] = $imageName;
        $request->picture->move(public_path('msg'), $imageName);
    }
    if ($request->hasFile('images')) {
        $filenamewithExt = $request->file('images')->getClientOriginalName();
        $filname = pathinfo($filenamewithExt,PATHINFO_FILENAME);
        $extension =$request->file('images')->getClientOriginalExtension();
        $filenametostore = $filname.'_'.time().'.'.$extension;
        $path =$request->file('images')->storeAs('public/cover_images',$filenametostore);
        
    }
    images::create($request->all());
    return response()->json(['success' => $imageName]);
}

Route::post('/saveimages', 'EmployeesController@saveimages')->name('saveimages');

After that Iam getting this error on the browser

message: "Call to a member function getClientOriginalExtension() on null" exception: "Symfony\Component\Debug\Exception\FatalThrowableError" file: "C:\xampp\htdocs\company\app\Http\Controllers\EmployeesController.php"

0 likes
5 replies
123ali's avatar

I am try this method but I am again getting this error in browser

    if(!empty($data['images'])){
        $imageName = time().'.'.$request->file('images')->getClientOriginalExtension();
        $request['images'] = $imageName;
        $request->file('images')->move(public_path('msg'), $imageName);
    }

message: "Call to a member function getClientOriginalExtension() on null" exception: "Symfony\Component\Debug\Exception\FatalThrowableError" file: "C:\xampp\htdocs\company\app\Http\Controllers\EmployeesController.php"

But when we try try to use this way of code then we get the this error

    if(!empty($data['images'])){
        $imageName = time().'.'.$request->images->getClientOriginalExtension();
        $request['images'] = $imageName;
        $request->images->move(public_path('msg'), $imageName);
    }

message: "Call to a member function getClientOriginalExtension() on string" exception: "Symfony\Component\Debug\Exception\FatalThrowableError" file: "C:\xampp\htdocs\company\app\Http\Controllers\EmployeesController.php" line: 42

can you help to solve this problem I am new at laravel to development tool platform

vevers's avatar

Could it be that you're uploading the base64 string of the image instead? (reader.readAsDataURL) Try a dd($data['images']) and let us know what it returns.

If it indeed is base64, then you can easily store it like this: Storage::disk('public')->put($fileName,base64_decode($fileData)); (And add some guards to validate $fileData is a string starting with a base64 prefix.)

123ali's avatar

yes I am try to upload base64 image ?

vevers's avatar

Base64 always uses a format like this: data:image/png;base64,iVBORw0KGgoAA...... You could try something like this:

    $base64Image = $data['images'];

    //Simple check to validate if this is a base64 string
    if(!starts_with($base64Image, 'data:')) throw new \Exception('Not a valid base64 string');

    /*
     * Write your own simple method to get the file extension from the base64 string
     * 'data:image/png;...' ==> 'png'
     */
    $fileExtension = $this->getFileExtensionFromBase64($base64Image);

    //Convert base64 to binary filedata (might want to wrap this in a try catch, to catch exceptions)
    $fileData = base64_decode($base64Image);

    //Store to disk
    Storage::disk('public')->put($fileName . "." . $fileExtension, $fileData);

Alternatively, you could also use the Intervention Image package, which supports generating images from base64 out of the box:

    //Generate image object from base64 string
    /** @var \Intervention\Image\Image $image */
    $image = Image::make($base64Image);
    $image->encode($fileFormatToUse, 90);
    
    //Optionally put your code to crop/resize/etc. here
    //....
    
    //Store
    $image->save(public_path($pathToSaveTo));

See http://image.intervention.io/getting_started/introduction for the full documentation.

Please or to participate in this conversation.