Laravel将图片存入3个public子文件夹失败,求解决方案(附代码)
问题
需要将图片存储到public目录下的3个不同子文件夹中,目前已实现存入两个文件夹,但添加第三个文件夹路径后,图片无法复制到第三个文件夹。
可行的双文件夹复制代码
$input['student_photo'] = time().'.'.$request->student_photo->getClientOriginalExtension(); $folder1 = public_path('public/path1/'); $path1 = $folder1 . $input['student_photo']; // path 1 $request->student_photo->move($folder1, $input['student_photo']); // image saved in first folder $path2 = public_path('public/path2/') . $input['student_photo']; // path 2 \File::copy($path1, $path2);
尝试的三文件夹代码(无效)
$input['student_photo'] = time().'.'.$request->student_photo->getClientOriginalExtension(); $folder1 = public_path('public/path1/'); $path1 = $folder1 . $input['student_photo']; // path 1 $request->student_photo->move($folder1, $input['student_photo']); // image saved in first folder $path2 = public_path('public/path2/') . $input['student_photo']; // path 2 $path3 = public_path('public/path3/') . $input['student_photo']; // path 3 \File::copy($path1, $path2, $path3);
解决方法
File::copy()参数错误:Laravel的File::copy()方法仅接受两个参数——源文件路径和单个目标文件路径,无法一次性传入多个目标路径。要复制到第三个文件夹,需单独调用一次File::copy()。路径冗余问题:
public_path()本身已经指向项目根目录下的public文件夹,所以public_path('public/path1/')会生成项目根目录/public/public/path1/这种错误路径,应改为public_path('path1/'),避免路径不存在导致复制失败。检查目标文件夹是否存在:如果目标文件夹(如
path3)未创建,复制操作会失败。可以用File::makeDirectory()确保文件夹存在,第二个参数设为true支持递归创建子目录,第三个参数设为0755设置权限。
修正后的代码
$input['student_photo'] = time().'.'.$request->student_photo->getClientOriginalExtension(); // 定义文件夹路径,修正public_path的冗余问题 $folder1 = public_path('path1/'); $folder2 = public_path('path2/'); $folder3 = public_path('path3/'); // 确保所有目标文件夹存在 \File::makeDirectory($folder1, 0755, true, true); \File::makeDirectory($folder2, 0755, true, true); \File::makeDirectory($folder3, 0755, true, true); // 先将图片移动到第一个文件夹 $path1 = $folder1 . $input['student_photo']; $request->student_photo->move($folder1, $input['student_photo']); // 分别复制到第二个和第三个文件夹 $path2 = $folder2 . $input['student_photo']; \File::copy($path1, $path2); $path3 = $folder3 . $input['student_photo']; \File::copy($path1, $path3);
内容的提问来源于stack exchange,提问作者user12931578
相关产品推荐
相关产品推荐

