Laravel 8 报错Undefined offset:300,图片上传功能问题求助
解决Laravel控制器中
Undefined offset: 300错误的问题 你遇到的这个错误其实是个典型的变量混淆小失误,我来帮你拆解清楚:
错误核心原因
在你的resize私有方法里,你初始化了要返回的$images数组,但在循环处理不同尺寸图片时,你把生成的路径存到了**临时变量$image**里,而非最终要返回的$images数组。这就导致最终返回的$images里只有original这一个键,完全没有300、600、900这些尺寸对应的键。
当你在uploadImages方法里尝试访问$url['images'][$sizes[0]](也就是300这个键)时,数组里根本找不到这个键,自然就抛出了Undefined offset: 300的错误。
修复后的代码
只需要把resize方法里的$image[$size]改成$images[$size],确保所有尺寸的路径都被存入返回的数组中:
class AdminController extends Controller { protected function uploadImages($file) { $year = Carbon::now()->year; $imagePath = "/upload/images/{$year}/"; $filename = $file->getClientOriginalName(); $file = $file->move(public_path($imagePath), $filename); $sizes = ["300","600","900"]; $url['images'] = $this->resize($file->getRealPath(), $sizes, $imagePath, $filename); $url['thumb'] = $url['images'][$sizes[0]]; dd($url); } private function resize($path, $sizes, $imagePath, $filename) { $images['original'] = $imagePath . $filename; foreach($sizes as $size) { // 修正变量名,把路径存入$images数组 $images[$size] = $imagePath . "{$size}" . $filename; Image::make($path)->resize($size, null, function($constraint){ $constraint->aspectRatio(); })->save(public_path($images[$size])); } return $images; } }
额外优化建议
另外提个实用小建议:当前代码直接使用上传文件的原始文件名,很容易出现同名文件被覆盖的问题。你可以生成唯一文件名来避免这个情况,比如结合时间戳和随机字符串:
// 替换原来的$filename赋值 use Illuminate\Support\Str; $filename = time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
这样就能保证每个上传的文件名都是唯一的,不会覆盖之前的文件。
内容的提问来源于stack exchange,提问作者user9259038
相关产品推荐
相关产品推荐

