繁体   English   中英

如何在Laravel中验证文件上传

[英]How to Validate File Upload in Laravel [duplicate]

这个问题已经在这里有了答案:

我已经完成了一个上传图像文件的教程 当用户上传大于2MB的文件时,如何在视图中验证文件上传?

create.blade.php

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <strong>Whoops!</strong> Errors.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif
<div class="form-group">
    <input type="file" name="photos[]" multiple aria-describedby="fileHelp"/>
    <small id="fileHelp" class="form-text text-muted">jpeg, png, bmp - 2MB.</small>
</div>

规则

public function rules()
{
    $rules = [
        'header' => 'required|max:255',
        'description' => 'required',
        'date' => 'required',
    ];
    $photos = $this->input('photos');
    foreach (range(0, $photos) as $index) {
        $rules['photos.' . $index] = 'image|mimes:jpeg,bmp,png|max:2000';
    }

    return $rules;
}

一切正常,但是当我尝试上传大于2MB的文件时,出现错误:

照亮\\ Http \\异常\\ PostTooLargeException没有消息

我该如何解决并确保此异常?

在laravel中,您无法在控制器中处理这种情况,因为它不会进入控制器/ customrequest,并且将在中间件中处理,因此您可以在ValidatePostSize.php文件中进行处理:

public function handle($request, Closure $next)
 {
  //       if ($request->server('CONTENT_LENGTH') > $this->getPostMaxSize()) 
            {
             //            throw new PostTooLargeException;
  //        }

   return $next($request);
 }



/**
 * Determine the server 'post_max_size' as bytes.
 *
 * @return int
 */
protected function getPostMaxSize()
{
    if (is_numeric($postMaxSize = ini_get('post_max_size'))) {
        return (int) $postMaxSize;
    }

    $metric = strtoupper(substr($postMaxSize, -1));

    switch ($metric) {
        case 'K':
            return (int) $postMaxSize * 1024;
        case 'M':
            return (int) $postMaxSize * 1048576;
        default:
            return (int) $postMaxSize;
    }
}

与您的自定义消息

或在App \\ Exceptions \\ Handler中:

   public function render($request, Exception $exception)
   {
      if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) {
        // handle response accordingly
      }
      return parent::render($request, $exception);
   }

否则需要更新php.ini

upload_max_filesize = 10MB

如果您不使用上述任何解决方案,则可以使用客户端验证,例如,如果使用的是jQuery,例如:

$(document).on("change", "#elementId", function(e) {
 if(this.files[0].size > 7244183)  //set required file size 2048 ( 2MB )
  { 
     alert("The file size is too larage");
    $('#elemendId').value = ""; 
  }
});

要么

<script type="text/javascript"> 
 function ValidateSize(file) { 
   var FileSize = file.files[0].size / 1024 / 1024; // in MB 
   if (FileSize > 2) { 
     alert('File size exceeds 2 MB'); 
      $(file).val(''); //for clearing with Jquery 
   } else { 

   } 
 } 
</script>

Laravel使用其ValidatePostSize中间件来检查请求的post_max_size,如果请求的CONTENT_LENGTH太大,则抛出PostTooLargeException。 这意味着该异常在到达控制器之前就被抛出了。

您可以做的是在App \\ Exceptions \\ Handler中使用render()方法,例如

public function render($request, Exception $exception){
   if ($exception instanceof PostTooLargeException) {
      return response('File too large!', 422);
   }

   return parent::render($request, $exception);
}

请注意,您必须从此方法返回响应,不能像从控制器方法那样仅返回字符串。

上面的响应是复制返回“文件太大!”; 您在问题中的示例中,显然可以将其更改为其他内容。

希望这可以帮助!

您可以尝试将自定义消息放入message()消息中,或在Handler类中添加PostTooLargeException处理程序。 像这样:

public function render($request, Exception $exception)
{
...
    if($exception instanceof PostTooLargeException){
                return redirect()->back()->withErrors("Size of attached file should be less ".ini_get("upload_max_filesize")."B", 'addNote');
        }
...
}

您已经在$ rules中验证了图片。 试试这个代码:

$this->validate($request,[
                'header' => 'required|max:255',
                'description' => 'required',
                'date' => 'required',
                'photos.*' => 'image|mimes:jpeg,bmp,png|max:2000',
    ]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM