简体   繁体   中英

Laravel 5.1 file upload, File's same name for folder and database

My controller code where i store the file name into a database table and also moving the file to a folder.

The issue is that i am storing the original name of a file in database table, in contrast i am moving files with uniqueid() and time() . It will arise issues in future. because in database table file name and moved file are with different names.

if(Input::hasFile('profile_pic')){
            $pic = Input::file('profile_pic');
            $mobile->photo1 = $pic[0]->getClientOriginalName();
            $mobile->photo2 = $pic[1]->getClientOriginalName();
            $mobile->photo3 = $pic[2]->getClientOriginalName();
            $mobile->photo4 = $pic[3]->getClientOriginalName();
            $mobile->photo5 = $pic[4]->getClientOriginalName();
                foreach ($pic as $k=>$file){
                    if(!empty($file)){
                        $file->move(public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop');
                    }
                }
        }

You can store both names in your database. Store one as original_name and one as generated_name for example.

And you can serve the file with the original name by retrieving it from the database if you want to let your users download it. It should look like this:

$photo = Photo::find(1);
return response()->download($photo->generated_filename, $photo->filename);

You can try to use something like that:

if(Input::hasFile('profile_pic')){
    $pic = Input::file('profile_pic');
    foreach ($pic as $k=>$file){
        if(!empty($file)){
            $temp = $k+1;
            $mobile->photo.$temp = time() . uniqid() . '-' . $k . '-laptop';
            $file->move(public_path() . '/uploads/', $mobile->photo.$temp);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM