3

I'm looking at being able to have a image detect in a global middleware on Laravel.

My goal is to make the middleware, detect if there is currently an image being uploaded, and then detect its size and manipulate it.

Is this possible?

I've inherited a project, and need to manipulate every global image upload, but there are far too many individual scripts to change them all separately, I need some sort of way to change them all globally.

I'm open to suggestions!

Pradeep
  • 9,667
  • 13
  • 27
  • 34
S_R
  • 1,818
  • 4
  • 27
  • 63

1 Answers1

1
<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\Response;

class ImageInterceptorMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach (array_flatten($request->files->all()) as $file) {
            $size = $file->getClientSize(); // size in bytes!

            $onemb = pow(1024, 2); // https://stackoverflow.com/a/2510446/6056864

            if ($size > $onemb) {
                abort(Response::HTTP_UNPROCESSABLE_ENTITY);
            }
        }

        return $next($request);
    }
}
Quezler
  • 2,376
  • 14
  • 29
  • I don't want to actually handle the upload in the middleware, I just want to check its of a certain size before continuing. To do this, could I just have the top function, and return next request if the size it ok, to allow whatever controller made the request to finish the upload? – S_R May 04 '18 at 11:16
  • @S_R i have updated the middleware to check filesize instead – Quezler May 04 '18 at 11:23
  • *note:* it checks the size of each file individually, and if any of them is to big the entire request gets blocked, not just that single file. – Quezler May 04 '18 at 11:25
  • This seems to be checking the php.ini file for the allowed file size, not what is specified in the code. It returns `The file "picture.jpg" exceeds your upload_max_filesize ini directive (limit is 2048 KiB).` – S_R May 04 '18 at 11:35
  • @S_R no, you appear to have configured your php to only accept files up to 2 mb, only files below it get sent to this code. (you'd have to increase the default upload size) – Quezler May 04 '18 at 11:55
  • Thank you, you are correct. Although the getClientSize() function is returning the error `Call to a member function getClientSize() on array` – S_R May 04 '18 at 13:14
  • Oh that is odd? could you try `$request->files->all()` ? – Quezler May 04 '18 at 13:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170376/discussion-between-s-r-and-quezler). – S_R May 04 '18 at 13:18