【问题标题】:Generate image extension from mimetype从 mimetype 生成图像扩展
【发布时间】:2015-07-24 04:43:54
【问题描述】:

我一直在尝试在 Laravel 5 中上传图像(通过 laravelcollective/forms 生成的上传,并使用干预图像库进行处理)。 我想做的是当用户上传任何照片时,我想根据其 mimetype 设置扩展。应该有一些基本的检查来防止虚假数据注入。

$file_profile_image->getClientMimeType();

为此,我是否应该像这样进行映射?

['image/jpeg' => 'jpg', 'image/gif'=> 'gif']

【问题讨论】:

  • Laravel File 对象有一个方法来解决这个问题。您所要做的就是致电$file_profile_image->guessExtension()

标签: security laravel-5 mime-types image-uploading dummy-data


【解决方案1】:

文件对象有一个专门用于这种情况的方法。您所要做的就是像这样在文件对象上调用guessExtension 方法

$file_profile_image->guessExtension()

【讨论】:

    【解决方案2】:

    我会使用 Intervention 包来检查您是否正在加载有效的图像并从那里获取 mime。

    类似这样的:

    /**
     * Store a file
     *
     * @return Response
     */
    public function store(Filesystem $filesystem)
    {
        // check if file was posted
    
        $uploadedFile = Request::file('file');
    
        // other checks here, ->isValid() && filesize
    
        try {
            $image = Image::make(\File::get($uploadedFile));
        } catch (\Intervention\Image\Exception\NotReadableException $e) {
            \Log::error('Unsupported filetype');
            dd('Unsupported filetype');
            // return proper error here
        }
    
        // mime as returned by Intervention
        $mime = $image->mime();
    
        // other stuff
        // store @ fs
    }
    

    【讨论】:

    • 谢谢你……我喜欢轻量级的实现。阅读干预文档,我发现它将以给定的扩展格式保存图像(如果未提供,则回退到图像默认值)。
    【解决方案3】:

    我会这样做:

    $source_file = $request->file('image')->getRealPath();
    $info = get_image_details($source_file);
    

    get_image_details($path)函数可以定义如下:

    function get_image_details($path)
    {
        $details = @getimagesize( $path );
    
        if ( is_array($details) && count($details) > 2 ) {
    
            $info = [
                'width' => $details[0],
                'height' => $details[1],
                'mime' => $details['mime'],
                'size' => @filesize($path),
                'path' => $path,
            ];
    
            switch ($details['2']) {
                case IMG_PNG:
                case 3:
                    $info['type'] = 'png';
                break;
    
                case IMG_JPG:
                case 2:
                    $info['type'] = 'jpg';
                break;
    
                case IMG_GIF:
                case 1:
                    $info['type'] = 'gif';
                break;
    
                default:
                    $info['type'] = $details[2];
                break;
            }
    
            return $info;
        }
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 2011-04-24
      • 1970-01-01
      相关资源
      最近更新 更多