Laravel图像上传验证

时间:2017-03-06 04:50:15

标签: php laravel validation laravel-5

我正在尝试使用laravel验证来验证上传的文件,但我遇到了问题。

这是我的代码:

$this->validate($request, [
        'image' =>'mimetypes:image/jpeg,image/png,image/gif',

        ]);

        $avatar = $request->file('image');

        $fileName = time(). '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar)->resize(300,300)->save( public_path('uploads/avatar/' . $fileName));

        $user = Auth::user();
        $user->avatar = $fileName;
        $user->save();

问题是当我使用bmp文件时,我收到此错误: Gd error

我正在使用Intervention图像包。我宁愿不切换到想象力的驱动程序。

有什么想法吗?

4 个答案:

答案 0 :(得分:0)

查看干预包代码,您可以看到 processBmp 函数的两个实现:

干预/图像/ GD / Encoder.php:

protected function processBmp()
{
    throw new \Intervention\Image\Exception\NotSupportedException(
        "BMP format is not supported by Gd Driver."
    );
}

干预/图像/ Imagick / Encoder.php:

protected function processBmp()
{
    $format = 'bmp';
    $compression = \Imagick::COMPRESSION_UNDEFINED;
    $imagick = $this->image->getCore();
    $imagick->setFormat($format);
    $imagick->setImageFormat($format);
    $imagick->setCompression($compression);
    $imagick->setImageCompression($compression);
    return $imagick->getImagesBlob();
}

所以我认为可以安全地说你不能用GD驱动程序来做,只能用想象力。

答案 1 :(得分:0)

只需使用"intervention/image": "~2"或将您的驱动程序更改为Imagick即可。 GD本身不支持BMP是一个众所周知的问题。您可以查看issue page on github了解详情。

答案 2 :(得分:0)

为什么不对图像image使用Laravel自定义规则?

$this->validate($request, [
        'image' =>'image',

        ]);

答案 3 :(得分:0)

希望此解决方案能够解决您的错误,请尝试使用以下逻辑

 public function postUpload(Request $request)
    {

    $input = $request->all();
    $rules = array(
      'uploadFile' => 'image|max:8000'
    );

    $validation = Validator::make($input, $rules);

    if ($validation->fails())
    {
      return array(
          'validation_failed' => true,
          'errors'            => $validation->errors()->toArray()
      );
    }

    $file = $request->uploadFile;
    $destinationPath = 'uploads/img';

    // Get real extension according to mime type
    $ext = $file->extension();
    // Hash processed file name, including the real extension
        $hashname           = date('H.i.s').'-'.md5($request->_token).'.'.$ext;
        $upload_success     = $request->uploadFile->storeAs($destinationPath, $hashname);


        Image::configure(array('driver' => 'imagick'));
        $img = Image::make(storage_path() . '/app/uploads/img/' . $hashname);
        $img->resize(230, null, function ($constraint) {
                $constraint->aspectRatio();
        });
        $img->save(storage_path() . '/app/uploads/lowres/' .$hashname ,80);

        $user_image = new User_images();
        $user_image->id_user = Auth::user()->id;
        $user_image->handler = $hashname;
        $user_image->save();


        return array('status' => 'success','message'=> 'Image has been uploaded successfully','file_path'=>'/uploads/'.$hashname);