如何将文件上传更改为仅图像上传,Laravel

时间:2018-02-23 12:37:45

标签: javascript php laravel

所以我有这个表单可以让你选择文件的工作,但我如何使它只接受图像而不是文件因为我现在接受所有东西......所以我该怎么做?或者我应该将选择文件按钮更改为图像按钮?这就是我做的事情

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>

1 个答案:

答案 0 :(得分:2)

尝试以下代码。将所有html属性添加为assoc数组。

{!! 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() !!}