php - 如何使文件只上传图片 - Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46029622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:35:54  来源:igfitidea点击:

php - How to make file uploaded only image - Laravel

phpimagelaravelphoto

提问by Sahat Riyanto

Hello im newbie in laravel so i really need some help. I want to create a code where only the image that can upload other files can not, I have tried to use the code input file but when I try to upload the zip file file it still uploaded so I really need help

你好,我是 laravel 的新手,所以我真的需要一些帮助。我想创建一个代码,其中只有可以上传其他文件的图像不能,我尝试使用代码输入文件,但是当我尝试上传 zip 文件时,它仍然上传,所以我真的需要帮助

This is my table code

这是我的表代码

<div class="col-sm-5">
{!! Form::label('photo', 'Photo:') !!}
<input type='file' name='photo' class='form-control' accept = 'image/jpeg , image/jpg, image/gif, image/png'>

And this is my Controller

这是我的控制器

    public function store(CreateBannerRequest $request)
{

    $input = $request->all();
    //get original file name
    if($request->photo == NULL)
    {
        Flash::error('Image must be filled');
        return back();
    }
    $filename = Input::file('photo')->getClientOriginalName();
    $input['photo'] =  $filename;
     $banner = $this->BannerRepository->create($input);
    //upload file
    Input::file('photo')->move($this->path, $filename); 

     Flash::success('Banner saved successfully.');

     if (empty($banner)) {
        Flash::error('No image available');

        return redirect(route('banner.index'));
    }

     return redirect(route('banner.index'));
}

This is the view of my code

这是我的代码视图

回答by Sagar Gautam

You have code at front end like this:

你在前端有这样的代码:

View

看法

<form action="{{URL::to('upload/photo')}}" class="form-horizontal" method="POST" role="form" enctype="multipart/form-data">
    <input type="file" name="photo">
    <button class="btn btn-default pull-right" type="submit">Create</button>
</form>

Route

路线

Route::post('upload/photo','TestController@uploadPhoto');

TestController

测试控制器

public function uploadPhoto(Request $request)
{
    $this->validate($request, [
        'photo' => 'mimes:jpeg,png,bmp,tiff |max:4096',
    ],
        $messages = [
            'required' => 'The :attribute field is required.',
            'mimes' => 'Only jpeg, png, bmp,tiff are allowed.'
        ]
    );
 // Now save your file to the storage and file details at database.
}

I hope, you undestand.

我希望,你明白。

回答by Sari Yono

you can do it with validation throuhg mimes:jpegand the other types such as png etc. lookup laravel validation on the documentation page

您可以通过验证通过验证mimes:jpeg和其他类型(例如 png 等)来完成。在文档页面上查找 Laravel 验证