Summer Sale! All accounts are 50% off this week.

mecjos's avatar

Get files in base64 code

Hi. I want to send any type of file via filereader from javascript to laravel backend. I use following code at javascript side.

var fileReader = new FileReader();

        fileReader.onload = ( function () {

            filesToUpload.push({ id : index, fileData : fileReader.result });

        });

        fileReader.readAsDataURL(value);

I can send data in base64 format but I don't know how can I save this data at laravel side. Could someone give an example. Thank you.

0 likes
8 replies
tokoiwesley's avatar

You can as well store the data URL in the database as a string $table->text('file_data');

1 like
mecjos's avatar

thanks for the link nikos. I have problem with getin the array. I add filesToUpload array into form with following code.

if (filesToUpload) {

            formDatas.append('cadNames[]', filesToUpload);

        }

I can't get the content of cadNames[] array wit following backend code.

if ($request->get("cadNames")) {

        $cadFiles = $request->get('cadNames');

        foreach ($cadFiles as $index => $object) {

            echo $index . json_decode($object);
        }

    } else {

        echo "cadNames null";
    }
nsvetozarevic's avatar

Or hence its base64, you could try $request->input('cadNames'). One of those must work

mecjos's avatar

@nikos I can det with $request->get('cadNames') or input('cadNames')..

if ($request->get("cadNames")) {

        $cadFiles = $request->input('cadNames');

        echo gettype($cadFiles);

    } else {

        echo "cadNames yok";
    }

cadNames is an array and it has filesToUpload array which contains json data object in following form

filesToUpload.push({ "id" : index, "fileType" : fileExtension, "fileData" : fileReader.result.split(',')[1] });

I can't get id, fileExtension and file data props at laravel side. That's my problem

mecjos's avatar
mecjos
OP
Best Answer
Level 2

@NIKOS - I updated my code into

filesToUpload = [];

$.each(event.target.files, function(index, file){

        filesToUpload.push(file);

}

then I append this fileToUpload Array into form data :

if (filesToUpload) {

            formDatas.append('cadNames', filesToUpload);

}

When I get that cadNames with $request in controller :

if ($request->get("cadNames")) {

        return $request->get('cadNames');

    }

I get following response :

["[object File],[object File]"] 0: "[object File],[object File]" length: 1 proto: Array(0)

Please or to participate in this conversation.