将相同名称存储到数据库和存储目录

时间:2017-02-24 15:59:44

标签: laravel laravel-5.3

在保存文件时,我很难将相同的文件名存储到本地存储和数据库中。截至目前,我正在使用storeAs函数存储文件上传,我为上传的文件传递了一个名称,但是当我检查我的数据库时,名称不同,它生成的内容类似于/tmp/phpGiNhTv。如何使用与本地存储中的文件相同的名称将文件保存到数据库?

示例代码:

public function store(Project $project)
    {
        $this->validate(request(),[
                'name' => 'required|min:8',
                'category' => 'required',
                'thumb' => 'required'
            ]);

        if( request()->hasFile('thumb') ) {
            $file = request()->file('thumb');
            $extension = $file->getClientOriginalName();
            $destination = 'images/projects/';
            $filename = uniqid() . '.' . $extension;
            $file->move($destination, $filename);
            $new_file = new Project();
            $new_file->thumb = $filename;
            $new_file->save();
        }

        Project::create(request()->all());
        return redirect('/projects');
    }
  

另外,此文件上载包含表单内的其他字段   其他字段也应保存到数据库。

2 个答案:

答案 0 :(得分:1)

  

您可以使用uniqueid()获取上传文件的唯一名称,然后与文件的原始扩展名连接,然后将其存储到本地存储,然后存储到数据库。

if($request->hasFile('thumb')){
    $file = request()->file('thumb');
    $extension = file->getClientOriginalExtension();
    $destination = 'images/';
    $filename = uniqid() . '.' . $extension;
    $file->move($destination, $filename);

/*
 * To store in to database
 * you can use model of database and store in it.
 * Eg. File Model.
 */

$new_file = new File();
$new_file->filename = $filename;
$new_file->save();
}

答案 1 :(得分:1)

if( request()->hasFile('thumb') ) {

    $file = request()->file('thumb');

    //Relative upload location (public folder)
    $upload_path = 'foo/bar/';

    //separete in an array with image name and extension
    $name = explode('.', $file->getClientOriginalName());

    //1 - sanitaze the image name
    //2 - add an unique id to avoid same name images
    //3 - put the image extension
    $imageName = str_slug($name[0]) . '_' . uniqid() . '.' . $file->getClientOriginalExtension();

    //Here you have the upload relative path with the image name
    //Ex: image/catalog/your-file-name_21321312312.jpg
    $file_with_path = $upload_path . $imagename;

    //Move the tmp file to a permanent file
    $file->move(base_path() . $upload_path, $imageName);

    //Now you use the file_with_path to save in your DB
    //Example with Eloquent
    \App\Project::create([
        'name' => $imageName,
        'path' => $file_with_path
    ]);
}

如果您打算使用Eloquent示例,请记住在模型中设置质量分配变量

https://laravel.com/docs/5.4/eloquent#mass-assignment