草庐IT

php - Laravel 5.3 - 图像验证不工作

coder 2024-04-26 原文

我对图像或 mime 的总体验证有疑问。

这是我的代码:

$this->validate($request, [
        'title' => 'required|max:50',
        'content' => 'required|min:20',
        'description' => 'required|max:140',
        'file' => 'image'
    ]);

当我尝试上传任何文件时出现错误:

The file failed to upload.

当我没有 image 标志时,一切正常。

我可以输入诸如 requiredmax:5000 之类的内容。

我查看了文档,它应该可以工作,但没有。

那我做错了什么?

编辑:

添加的形式:

 {!! Form::open(['method' => 'POST', 'action' => 'PostController@store', 'files' => 'true' ]) !!}

            <div class="form-group">

                {!! Form::label('title', 'Title:') !!}<br>
                {!! Form::text('title', null, ['class' => 'form-control']) !!}
                <small>Max 50 characters</small>

                <br>

                {!! Form::label('description', 'Description:') !!}<br>
                {!! Form::textarea('description', null, ['class' => 'form-control', 'rows' => 2, 'cols' => 50]) !!}
                <small>Max 140 characters</small>

                <br>

                {!! Form::label('content', 'Content:') !!}<br>
                {!! Form::textarea('content', null, ['class' => 'form-control', 'id' =>'content', 'rows' => 8, 'cols' => 50]) !!}

                <br>

                {!! Form::label('file', 'Upload a thumbnail here:') !!} <br>
                {!! Form::file('file', null, ['class' => 'form-control']) !!} <br>
                <small>Only jpeg, png, bmp, gif, or svg</small>

            </div>

                {!! Form::submit(null, ['class' => 'btn btn-primary']) !!}

                {!! Form::close() !!}

编辑 2:

添加了 html:

<form method="POST" action="https://blog.luukwuijster.eu" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden" value="N72xyc8mmbdFGrS78sdhIqh25awN30AboL9ecqGm">

            <div class="form-group">

                <label for="title">Title:</label><br>
                <input class="form-control" name="title" type="text" id="title">
                <small>Max 50 characters</small>

                <br>

                <label for="description">Description:</label><br>
                <textarea class="form-control" rows="2" cols="50" name="description" id="description"></textarea>
                <small>Max 140 characters</small>

                <br>

                <label for="content">Content:</label><br>
                <textarea class="form-control" id="content" rows="8" cols="50" name="content" style="display: none;"></textarea>

                <br>

                <label for="file">Upload a thumbnail here:</label> <br>
                <input name="file" type="file" id="file"> <br>
                <small>Only jpeg, png, bmp, gif, or svg</small>

            </div>

            <input class="btn btn-primary" type="submit">

            </form>

编辑 3:

添加了 Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use GrahamCampbell\Markdown\Facades\Markdown;

class PostController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */

public function __construct()
{
    $this->middleware('auth')->except('index', 'show');
}

public function index()
{

    $posts = Post::latest()->get();

    return view('welcome', compact('posts'));
}


/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('create');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $input = $request->all();

    $file = $request->file('file');

    if($file){
        $name = rand(1, 1000000000).'_'.$file->getClientOriginalName();

        $file->move('images', $name);

        $input['thumbnail'] = $name;
    }else{
        $input['thumbnail'] = "No_Image.png";
    }

    //TODO: validatie voor de thumbnails.

    $this->validate($request->all(), [
        'title' => 'required|max:50',
        'content' => 'required|min:20',
        'description' => 'required|max:140',
        'file' => 'image'
    ]);

    Auth::user()->post()->create($input);

    return redirect('/');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $post = Post::findOrFail($id);
    $content = Markdown::convertToHtml($post->content);

    return view('post', compact('post', 'content'));
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $post = Auth::user()->post()->findOrFail($id);
    return view('edit', compact('post'));
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $input = $request->all();

    $file = $request->file('file');

    if($file){
        $name = rand(1, 1000000000).'_'.$file->getClientOriginalName();

        $file->move('images', $name);

        $input['thumbnail'] = $name;
    }

    //TODO: validatie voor de thumbnails.

    $this->validate($request, [
        'title' => 'required|max:50',
        'content' => 'required|min:20',
        'description' => 'required|max:140',
        'file' => 'image'
    ]);

    Auth::user()->post()->findOrFail($id)->update($input);

    return redirect('/home');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    Auth::user()->post()->withTrashed()->findOrFail($id)->forceDelete();

    return redirect('/recyclebin');
}

public function restore($id)
{
    Auth::user()->post()->withTrashed()->findOrFail($id)->restore();

    return redirect('/home');
}

public function recyclebin()
{
    $posts = Post::onlyTrashed()->get();

    return view('recyclebin', compact('posts'));
}

public function remove($id){

    //Post::findOrFail($id)->delete();
    Auth::user()->post()->findOrFail($id)->delete();
    return redirect('/home');

}
}

最佳答案

在您的开始表单标签中添加:

enctype="multipart/form-data"

并在文件输入(您实际上传的位置)中添加:

multiple="multiple"

编辑: 在每种形式中,您都应该使用 csrf_field() 方法。也只在打开表单标签之前添加。

2019 年更新: 您可以添加 @csrf 指令而不是 csrf_field() 方法。一样,只是对某些人来说更方便。

希望对你有帮助。

关于php - Laravel 5.3 - 图像验证不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41523782/

有关php - Laravel 5.3 - 图像验证不工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  9. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  10. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

随机推荐