首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将相同的名称存储到数据库和存储目录

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

Stack Overflow用户
提问于 2017-02-24 15:59:44
回答 2查看 1.5K关注 0票数 0

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

样本代码:

代码语言:javascript
复制
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');
    }

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-24 16:49:00

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-02-24 17:18:22

代码语言:javascript
复制
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
    ]);
}

如果要使用雄辩的示例,请记住在模型中设置质量分配变量。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42443033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档