2017-02-24 104 views
0

我有一个很难存储相同的文件名,以我的本地存储和数据库时我保存文件。到目前为止,我正在使用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'); 
    } 

Additionaly,此文件上传包含一个表格,以便 等领域也应保存到数据库里面的其他领域。

回答

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(); 
} 
+0

不是为我工作PAL制式。它说'调用未定义的方法Illuminate \ Support \ Facades \ File :: save()'。 – claudios

+0

我删除最后3行并保存该文件,但不相同的名字在我的数据库 – claudios

+0

什么是它应该是文件到上面的代码 –

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 
    ]); 
} 

如果你要使用的雄辩例子,记得设置的质量分配变量模型

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

+0

感谢队友,但没有在我的工作。 '$ imageName'是未定义的变量。 – claudios