首页 > 解决方案 > Laravel 中的文件上传 - 如果用户尝试上传大文件,则向用户显示错误

问题描述

在 Laravel 中,我成功地让用户在页面上上传文件,但我想知道是否有办法在用户提交文件太大的页面之前向该用户显示错误。类似“您选择上传的文件为 25MB。将其下载到 20MB 以下。”

是否有某种包可以处理这个问题?

标签: laravelfileupload

解决方案


在客户端验证文件大小。(提到这一点是因为您提到您想在表单提交之前警告错误。)检查下面使用 jQuery 的示例代码:

$(document).ready(function() {

    $('input[type="file"]').change(function(event) {
        var fileSize = this.files[0].size;
        var maxAllowedSize = //add your value here;
        // check the file size if its greater than your requirement
        if(size > maxAllowedSize){
          alert('Please upload a smaller file');
          this.val('');
        }

    });
});

服务器端验证(您可以根据要允许的文件类型更改 mime 类型):

<?php 

public function store(Request $request){

    $request->validate([
        'file_input_name' => 'file|max:25000|mimes:jpeg,bmp,png',
        // add validations for other fields here
    ]);
}

更多检查文档


推荐阅读