Unable to read image from file. How to catch if image upload is unsuccessful
I have just had a notification from Sentry with the following error on my new app:
Intervention\Image\Exception\NotReadableException Unable to read image from file (/tmp/phpS1aKpd).
{
$rawImage = $file;
} else
{
$imagePath = $file->getRealPath();
$rawImage = \Image::make($imagePath); // this line is highlighted as the error
}
$rawImage->orientate();
$rawImage->resize(1000, null, function ($constraint) {
I was fortunate enough to be able to speak to the user who explained that they had uploaded an image on their phone from their icloud account when it threw the error. I realised that I didn't have mimes validation in place and now that it is the attempted image is not being accepted. My bad! :(
First question: in mimes validation, do I have to define jpg, jpeg, JPG etc or just jpg? Seems to work with but just wondering.
Secondly, is there a way to catch an error if the file does not get uploaded?
This is my code:
PortfolioController
public function store(Requests\StorePortfolio $request)
{
$user = \Auth::user();
$fileName = AssetManager::createFileName($user->publicName() . '-wedding-portfolio');
$request->merge(['fileName' => $fileName]);
$item = $user->professional->portfolio()->create($request->all());
$this->syncTags($item, (array) $request->input('tag_list'));
$path = $item->urlPath();
$variations = config('imagesizes.portfolio');
AssetManager::saveWithVariations($request->file, $path, $fileName, $variations);
return redirect()->route('professional-dashboard.portfolio.index');
}
AssetManager class
public static function saveWithVariations($file, $path, $fileName, $imageVariations, $visibilty = 'public')
{
if (isset($file->mime)) // is Intervention object
{
$rawImage = $file;
} else
{
$imagePath = $file->getRealPath();
$rawImage = \Image::make($imagePath);
}
$rawImage->orientate();
$rawImage->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode('jpg', 80);
$uploaded = AssetManager::saveToStorage(
$rawImage->stream()->__toString(),
$path . $fileName,
$visibilty
);
if ($uploaded)
{
foreach ($imageVariations as $key => $value) {
$image = $rawImage;
if ($uploaded)
{
if ($value['h'] == 'auto')
{
$image->resize($value['w'], null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
} else
{
$image->fit($value['w'], $value['h']);
}
$uploaded = AssetManager::saveToStorage(
$image->stream()->__toString(),
$path . $key . '-' . $fileName,
$visibilty
);
}
}
return $uploaded;
} else
{
return false;
}
}
I am thinking something like this in my PortfolioController which doesn't work for me.
try {
AssetManager::saveWithVariations($request->file, $path, $fileName, $variations);
} catch (Exception $e) {
// redirect back with errors
}
This is my first Laravel app and have learn't loads but still feel like this area could be a lot better.
Any advice appreciated.
Please or to participate in this conversation.