> 有必要考慮不是post請求或沒有指定enctype="multipart/form-data"的情況。如果是post請求還是設置了正確的編碼,沒有文件上傳時 request()->file('文件字段域') 會拋出異常,捕獲該異常即可。 **ThinkPHP6.0 判斷是否有文件上傳** ```php // 捕獲異常 try { // 此時可能會報錯 // 比如:上傳的文件過大,超出了配置文件中限制的大小 $file = request()->file('img'); // 如果表單沒有設置文件上傳需要的編碼 $file始終是null if (is_null($file)) { // 請檢查請求類型和表單編碼 // 不是post請求或沒有指定enctype="multipart/form-data"會進入這里 throw new \think\Exception('沒有文件上傳'); } } catch (\think\Exception $e) { // 獲取異常錯誤信息 halt($e->getMessage()); } ``` **如果表單請求類型是 `get`或沒有指定 `enctype="multipart/form-data"`** ```php request()->file('img');//始終返回 null ``` ```html <form action="" method="post"> <input type="file" name="img"> <button>立即上傳</button> </form> ```