我尝试使用Laravel 4上传文件,但我无法让验证工作正常。
我通过发送JPEG图像,PNG图像和MP3文件来测试它。我的代码如下:
$data = ['anexo' => Input::file('anexo')];
$rules = ['anexo' => 'mimes:jpeg'];
$validation = Validator::make($data, $rules);
if ($validation->fails())
{
// PNG fails: OK
}
else
{
// JPEG passes: OK
// MP3 passes: WTF?
}
// Let's see what the files looks like
var_dump($data);
以下是每个文件的 var_dump():
// JPEG
array (size=1)
'anexo' =>
object(Symfony\Component\HttpFoundation\File\UploadedFile)[9]
private 'test' => boolean false
private 'originalName' => string 'ARTcast.jpg' (length=11)
private 'mimeType' => string 'image/jpeg' (length=10)
private 'size' => int 310177
private 'error' => int 0
// PNG
array (size=1)
'anexo' =>
object(Symfony\Component\HttpFoundation\File\UploadedFile)[9]
private 'test' => boolean false
private 'originalName' => string '1280x800.png' (length=12)
private 'mimeType' => string 'image/png' (length=9)
private 'size' => int 426169
private 'error' => int 0
// MP3
array (size=1)
'anexo' =>
object(Symfony\Component\HttpFoundation\File\UploadedFile)[9]
private 'test' => boolean false
private 'originalName' => string '05 - Lado B Lado A.mp3' (length=22)
private 'mimeType' => string 'application/octet-stream' (length=24)
private 'size' => int 0
private 'error' => int 1
我在那里失踪的任何线索?
答案 0 :(得分:0)
mimeType
值,我无法在那里意识到"error" => int 1
。
所以这是一个解决方案,以防将来遇到同样的错误。另外,我发现了这个Symfony\Component\HttpFoundation\File\Exception\UploadException
异常,您可能会使用它来通知系统,并可能将其捕获到 globals.php 或其他地方。
$file = Input::file('input_name')
// checks for file upload errors
if (!$file->isValid())
{
throw new Symfony\Component\HttpFoundation\File\Exception\UploadException(
$file->getErrorMessage(),
$file->getError());
}
// continues with validation
$data = ['input_name' => $file];
$rules = ['input_name' => 'mimes:jpeg'];
$validation = Validator::make($data, $rules);
if($validation->fails())
{
// proceed with normal error treatment
}
再次注意, Laravel在验证时不会检查上传错误,您必须手动执行此操作。