Mohammad Mohammad - 28 days ago 10
JSON Question

How to get json file object and upload it in laravel

I want to upload an json file object in laravel , this object come from angular js with the below format:

{
"key": "lfobj2399fe3b",
"lfFile": {},
"lfFileName": "photo-1433354359170-23a4ae7338c6.jpg",
"lfDataUrl": "blob:http://localhost/14044b8b-9dcb-4461-8e2e-cf5337611396",
"element": {
"0": {
"ng339": 198
},
"length": 1
}
}


This is the plugin i've used to implement file upload in angular js :
https://github.com/shuyu/angular-material-fileinput

I've tried :

if ($request->hasFile('banners')) {
return \Response::json('file available',$statusCode);
}


to check if any file is available in my input but i got nothing.
if i want to get this object as an object i get it's value by using :

$banners = $request->input('banners');

but i can't upload any file with this input.
how can i get this object and upload it in laravel ?

Answer

For handling json objects you could use :

$request->input('object_name');

And for uploading from angular you could use form data request and then handle it in laravel like :

if (isset($_FILES['files']) && $_FILES['files']['error'] == 0) {

                ############ Edit settings ##############
                $UploadDirectory = '../public/images/banners/'; //specify upload directory ends with / (slash)

                ##########################################

                $NewFileName = strtolower($_FILES['files']['name']);

                //===========Remove the file if exist==============
                if(file_exists($UploadDirectory.$NewFileName)) {
                    unlink($UploadDirectory.$NewFileName);
                }
                //===========Remove the file if exist==============

                if (move_uploaded_file($_FILES['files']['tmp_name'], $UploadDirectory . $NewFileName)) {
                    $Access_Directory = "/images/banners/";
                    $file = $Access_Directory . $user_id . "/". $NewFileName;
                    return $file;

                }
            }

I've used this method and work pretty well actually.