如何从数据库复制图片到新路径?解决数组转字符串转换错误
解决“Array To String Conversion”错误的方案
你的错误根源在于这行代码:
$ext = explode('.', $img_name);
explode() 会把文件名按 . 分割成数组,但你后续直接把这个数组拼接到字符串里,PHP无法自动将数组转为字符串,因此抛出了类型转换错误。
修正方案1:取数组最后一个元素作为后缀
如果文件名里只有一个 .,可以用 end() 直接获取数组最后一项:
$record = AboutPageIntro::find($id); $img_name = $record->image; $ext = explode('.', $img_name); // 提取数组最后一个元素作为文件后缀 $file_ext = end($ext); Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $file_ext));
修正方案2:用pathinfo()更稳妥处理后缀
如果文件名可能包含多个 .(比如banner.v2.png),推荐用pathinfo()直接提取后缀,避免分割数组的麻烦:
$record = AboutPageIntro::find($id); $img_name = $record->image; // 直接获取文件扩展名 $file_ext = pathinfo($img_name, PATHINFO_EXTENSION); Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $file_ext));
内容的提问来源于stack exchange,提问作者procoder3000
相关产品推荐
相关产品推荐

