2017-02-24 119 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