laravel - Laravel 中的文件上传 - 如果用户尝试上传大文件,则向用户显示错误
问题描述
在 Laravel 中,我成功地让用户在页面上上传文件,但我想知道是否有办法在用户提交文件太大的页面之前向该用户显示错误。类似“您选择上传的文件为 25MB。将其下载到 20MB 以下。”
是否有某种包可以处理这个问题?
解决方案
在客户端验证文件大小。(提到这一点是因为您提到您想在表单提交之前警告错误。)检查下面使用 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
]);
}
更多检查文档
推荐阅读
- c# - 如何在 Unity 的 Roll-a-Ball 教程中在 Android 中获得等效的用户输入?
- javascript - 使用 Squeezebox 投资组合模板获取在新窗口中打开的链接
- elixir - 我应该如何管理插入相关表
- python - python for循环完成
- html - 如何将标题与图像顶部对齐(行高问题)
- macos - 如何以编程方式转储所有线程的调用堆栈,而不仅仅是当前线程 [NSThread callStackSymbols]
- ios - 多点连接的广告商帮助 swift 4
- python - 在终端中启动 pyspider 时出现 ImportError
- matlab - 在MATLAB中将矩阵位置乘以标量
- r - 我在 R 中创建散点图的命令不起作用