問題描述
我的網站托管在共享服務器上.最大上傳限制為 5MB.我無法更改 PHP ini 設置,這很好.
I have my website hosted at a shared server. The maximum upload limit is 5MB. I do not have the ability to change the PHP ini settings, which is fine.
在 Laravel 中,如果上傳的文件小于 5MB,所有驗證和文件上傳都可以正常工作.但是,當上傳大于 5MB 的文件時,我收到以下異常而不是驗證錯誤:
In Laravel, all the validations and file uploading works fine if the uploaded file is under 5MB. However, when a file greater than 5MB is uploaded, I get the following exception instead of a validation error:
如何驗證或強制文件低于服務器上傳限制?
How can I validate or force the file to be under the upload limit from server?
推薦答案
您似乎對更改 PHP 限制以允許更大的文件不感興趣.在我看來,您希望最大上傳大小為 5MB,如果超過,則返回正確的響應.
You don't seem interested in changing the PHP limits to allow larger files. It looks to me like you want your max upload to be 5MB, and return a proper response if it is over that.
您可以在 app/Exceptions/Handler.php
處的異常處理程序中處理 FileException
異常.更新 render
方法以添加您需要的代碼.例如,如果您想返回驗證異常,則需要在 FileException
異常的異常處理程序中處理驗證.
You can handle the FileException
exception inside your exception handler at app/Exceptions/Handler.php
. Update the render
method to add in the code you need. For example, if you'd like to return a validation exception, you will need to handle the validation inside the exception handler for the FileException
exception.
public function render($request, Exception $exception)
{
if ($exception instanceof SymfonyComponentHttpFoundationFileExceptionFileException) {
// create a validator and validate to throw a new ValidationException
return Validator::make($request->all(), [
'your_file_input' => 'required|file|size:5000',
])->validate();
}
return parent::render($request, $exception);
}
這是未經測試的,但應該可以讓您大致了解.
This is untested, but should give you the general idea.
您還可以通過 javascript 進行客戶端驗證,這樣過大??的文件實際上永遠不會發送到您的服務器,但是客戶端可以禁用或刪除 javascript,因此最好有一個不錯的服務器端處理設置.
You can also do client side validation via javascript, so that a file that is too large is never actually sent to your server, but javascript can be disabled or removed by the client, so it would be good to have nice server side handling set up.
對于客戶端驗證,如果您將事件處理程序附加到文件輸入的更改"事件,您可以使用 this.files[0].size
檢查文件大小,并且之后執行任何其他操作(禁用表單、刪除上傳的文件等)
For the client side validation, if you attach an event handler to the "change" event for the file input, you can check the file size using this.files[0].size
, and perform any additional actions after that (disable form, remove uploaded file, etc.)
這篇關于Laravel - 超過 PHP 最大上傳大小限制時驗證文件大小的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!