Laravel文件名数据库

时间:2016-10-04 09:50:05

标签: php laravel-5.3

public function upload(Request $request, User $user, $directory) { if($request->hasFile('attachment')) { $attachments = $request->file('attachment'); foreach ($attachments as $attachment) { $fileName = $attachment->store('users/' . $user->id . '/' . $directory); $file = new File; $file->path = $fileName; $file->user_id = $user->id; $this->files()->save($file); } } } 我上传这样的文件:

7b11ae012907b5811cb6985d39e16052

所以它的存储方式如下:

enter image description here

如何存储随机名称(路径)而不是整个路径?

(随机唯一名称类似于:lastLogon

2 个答案:

答案 0 :(得分:1)

public function upload(Request $request, User $user, $directory)
{
if($request->hasFile('attachment'))
{
    $random_name=rand(5, 15);
    $attachments = $request->file('attachment');
    foreach ($attachments as $attachment) {
        $fileName = $attachment->store('users/' . $user->id . '/' . $random_name);
        $file = new File;
        $file->path = $fileName;
        $file->user_id = $user->id;
        $this->files()->save($file);
    }
}

}

答案 1 :(得分:0)

我这样做了:

public function upload(Request $request, User $user, $directory)
{
    if($request->hasFile('attachment'))
    {
        $attachments = $request->file('attachment');
        foreach ($attachments as $attachment) {
            $random = str_random(30);
            $filename = $random . $attachment->getClientOriginalName();
            $attachment->storeAs('users/' . $user->id . '/' . $directory, $filename);
            $file = new File;
            $file->path = $filename;
            $file->user_id = $user->id;
            $this->files()->save($file);
        }
    }
}