0

So I have this form that lets you choose files its working but how do I make it only accepts images not files cause what I have now accepts everything... so how do I do it? or should I just change the choose file button to an image button? here's what I did

BuildingController.php

public function saveBuilding(Request $request)
    {
        $file = $request->file('buildingpics');
        $building = new Building();
        $building->name = $request->buildingname;

        $building->picture = $building->name.'.'.$file->getClientOriginalExtension();

        $file->move('assets',$building->name.'.'.$file->getClientOriginalExtension());

        $building->save();

       \Session::flash('building_flash', 'Created successfully!');

        return redirect('/');
    }

addbuilding.blade.php

<div class="form-group">
  {!! Form::label('Building Photo') !!}
  {!! Form::file('buildingpics',array('onchange'=>'previewFile()','required')) !!}
  <br/>
  <img src="../assets/imgholder.png" id="previewImg" style="height:300px; width:300px;" alt="">
</div>

script type="text/javascript">

function previewFile() {
var preview = document.querySelector('#previewImg');
var file    = document.querySelector('input[type=file]').files[0];
var reader  = new FileReader();

reader.addEventListener("load", function () {
  preview.src = reader.result;
}, false);

if (file) {
reader.readAsDataURL(file);
}
}
</script>
Doe
  • 31
  • 7
  • are you using laravel collective html forms? If yes can you try echo Form::file('image'); – harish durga Feb 23 '18 at 12:41
  • Validate your file using - https://stackoverflow.com/a/4237161/5735490 – Sheena Singla Feb 23 '18 at 12:45
  • The <input> element has an accept attribute which you can set and this will (in some browsers, mostly modern) allow the user to select file of a given type however you must ALWAYS do server side validation for the file type. Here's an example: https://www.w3schools.com/tags/att_input_accept.asp – Molik Miah Feb 23 '18 at 12:45

1 Answers1

3

Try the below code. Add the all the html attributes as an assoc array.

{!! Form::open(['url' => 'form','method' => 'post','files' => true]) !!}
    <?php
    echo Form::label("File Picker", null, ['class' => 'control-label']);
    echo Form::file("buildingpicks", $attributes = ['accept'=>"image/x-png,image/gif,image/jpeg"]);
    echo Form::submit('Submit');
?>
{!! Form::close() !!}
harish durga
  • 197
  • 1
  • 9
  • That is the syntax in documentation. And what is the error are you getting? – harish durga Feb 23 '18 at 13:07
  • have you set the files option to true? Form::open(['url' => 'foo/bar', 'files' => true]); – harish durga Feb 23 '18 at 13:10
  • should I replace `{!! Form::file('buildingpics',array('onchange'=>'previewFile()','required')) !!}` with yours? @harish durga how exactly should I do it? – Doe Feb 23 '18 at 13:26