这是一个简单的图片保存功能,其中包括原图片和压缩图片两种,目录结构是/images/year/month/xxx.png和/images/thumbnail/year/month/xxx.png;具体上传结果如下图所示:
upload_icon.pnguse Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
public function uploadImage(Request $request)
{
$inputData = $request->all();
if ($request->hasFile('file')) {
try {
$year = date("Y");
$month = "/images/$year/" . date("m");
$directory = Storage::exists($month);
if (!$directory) {
Storage::makeDirectory($month);
}
$apath = "/images/thumbnail/$year/" . date("m");
$thumbnail = Storage::exists($apath);
if (!$thumbnail) {
Storage::makeDirectory($apath);
}
$carid = strtoupper(md5(uniqid(mt_rand(), true)));
$uuid = substr($carid, 0, 8) . substr($carid, 8, 4) . substr($carid, 12, 4) . substr($carid, 16, 4) . substr($carid, 20, 12);
$file = $request->file('file');
$extension = strtolower($file->getClientOriginalExtension());
$photo = $inputData['file'];
$file_name = $uuid . "." . $extension;
$file_relative_path = 'storage/' . $month;
$file_path = public_path($file_relative_path);
if (!is_dir($file_path)) {
mkdir($file_path);
}
$relative_path = 'storage/' . $apath;
$thumbnail_path = public_path($relative_path);
$thumbnail_file_path = $thumbnail_path . '/' . $file_name;
$image = Image::make($photo)->resize(150, 150, function ($constraint) {
$constraint->aspectRatio();
})->save($thumbnail_file_path);
$file_path .= '/' . $file_name;
$image = Image::make($photo)->save($file_path);
$path = $month . "/" . $file_name;
if ($path) {
return ['success' => true, 'path' => $path];
} else {
return ['errors' => ['file' => 'uploaderror']];
}
} catch (\Exception $e) {
Log::error($e);
return ['errors' => ['file' => $e->getMessage()]];
}
} else {
return ['success' => false];
}
}
网友评论