首页 > 解决方案 > Laravel 5 | File upload - If file exists add number to filename

问题描述

I have problem with file upload. Now I have something like this (part of Controller):

if($request->has('photos')) {
            foreach ($request->photos as $photo) {
                $filename = $photo->getClientOriginalName();
                $tmp_name = $filename;

                if ($pos = strrpos($filename, '.')) {
                    $name = substr($filename, 0, $pos);
                    $ext = substr($filename, $pos);
                    
                } else {
                    $name = $filename;
                }

                $uniq_no = 0;
                while (file_exists($filename)) {
                    $tmp_name = $name .'_'. $uniq_no . $ext;
                    $uniq_no++;
                    
                }
                $photo->storeAs('public/photos/',$tmp_name);
                Photo::create([
                    'page_id' => $page->id,
                    'filename' => $tmp_name
                ]);
            }
        }

but saves to the database without adding a unique number: filename_0, filename_1 etc. It just saves the value of $tmp_name.

What am I doing wrong?

标签: laravellaravel-5file-uploadrequest

解决方案


我做了这样的事情:

if($request->has('photos')) {
            foreach ($request->photos as $photo) {
                $file = $photo->getClientOriginalName();
                $filename = pathinfo($file, PATHINFO_FILENAME).'_'.Str::random(6);
                $extension = pathinfo($file, PATHINFO_EXTENSION);
                $fullfilename = $filename .'.'. $extension;
                $photo->storeAs('public/photos/',$fullfilename);
                Photo::create([
                    'page_id' => $page->id,
                    'filename' => $fullfilename
                ]);
            }
        }

推荐阅读