簡體   English   中英

Laravel 5.2 + 上傳文件並在數據庫中保存名稱

[英]Laravel 5.2 + upload file and save name in database

在 laravel 5.2 中,我可以使用以下代碼上傳文件,但找不到將上傳的文件名存儲在數據庫中的方法。

    $destinationPath = "test/";
    $file = $request->file('profile_pic');
    if($file->isValid()){
        $file->move($destinationPath, $file->getClientOriginalName());
        $user = User::findOrFail(Auth::user()->id);
        $input = $request->all();
        $input['profile_pic']->pathname = $destinationPath.$file->getClientOriginalName();
        $user->update($request->all());
    }

有誰知道如何在數據庫中存儲文件名?

上傳文件/圖片並將實名寫入數據庫的代碼

public function store(Request $request)
{
    $data = $request->all();

    if($file = $request->file('your_file')){

        $name = $file->getClientOriginalName();
        $file->move('folder_where_to_save', $name);
        $data['your_file'] = $name;

    }

    Model_name::create($data); // where $data can be $request->all() or you can manually assign the fields you need
}

你可以試試這個,它會幫助你:

$destinationPath = "test/";
    $file = $request->file('profile_pic');
    if($file->isValid()){
        $file->move($destinationPath, $file->getClientOriginalName());
        $user = User::findOrFail(Auth::user()->id);
        $input = $request->all();
        $input['profile_pic']->pathname = $destinationPath.$file->getClientOriginalName();
        $user->update($request->all()); // Remove This

        // Add this lines

        $data['YOUR_DB_FIELD_NAME'] = $file->getClientOriginalName();
        $user->update($data);
    }

檢查這個完整的代碼

$destinationPath = 'uploads';
$extension = Input::file('prd_img')->getClientOriginalExtension(); 
$fileName = rand(11111,99999).'.'.$extension;
Input::file('prd_img')->move($destinationPath, $fileName);
$data = array(
    'prd_name' => $prd_name,
    'prd_cat' => $prd_cat,
    'prd_sub_cat' => $prd_sub_cat,
    'prd_img' => $fileName,
    'remember_token' => $remember_token,
    'created_at' => $time,
);
if(DB::table('products')->insert($data)){
    return redirect('add-product')->with('success', 'Product Succssfully Added.');
}else{
    return redirect('add-product')->with('error', 'Something wrong please try again.');
}

我明白了。 愚蠢的錯誤!

需要更換線路

$input['profile_pic']->pathname = $destinationPath.$file->getClientOriginalName();

$input['profile_pic'] = $destinationPath.$file->getClientOriginalName();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM