如何在 laravel 上上传文件并将其存储在目录中

Posted

技术标签:

【中文标题】如何在 laravel 上上传文件并将其存储在目录中【英文标题】:How to upload files on laravel and storing it in a directory 【发布时间】:2021-08-30 22:09:38 【问题描述】:

所以我在将我的用户图片存储在指定目录中时遇到了问题。图像已经在数据库中,但是当我调用数据时它没有显示任何内容。我如何将它存储在公用文件夹中,这里的数据库是我的代码行:

RegisterController.php

<?php

namespace App\Http\Controllers;

use Hash;
use App\Models\User;
use Illuminate\Http\Request;

class RegisterController extends Controller

  public function signin()
  
    return view('register', [
      'register' => true
    ]);
  

  public function register(Request $request)
  
    // Laravel Eloquent
    $user = User::where('email', $request->get('email'))->first();
    if ($user) 
      // if user / email exists
      return view('register', [
        'register' => false
      ]);
     else 
      // create user
      User::create([
        'name' => $request->get('name'),
        'email' => $request->get('email'),
        'password' => Hash::make($request->get('password')),
        'user_type' => 'admin',
        'bdate' => $request->get('bdate'),
        'contact_no' => '',
        'profile_image' => $request->file('profile_image')->store('http://localhost:8000/storage/images/'),
        //...
      ]);
  
      return redirect(route('login.login', ['registration' => 1]));
    
  

这是注册表

register.blade.php

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Register</title>

    <!-- Custom fonts for this template-->
    <link href="asset('dashboards/vendor/fontawesome-free/css/all.min.css')" rel="stylesheet" type="text/css">
    <link
        href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
        rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="asset('dashboards/css/sb-admin-2.min.css')" rel="stylesheet">

    <style>
        .new-bg-register-image 
             background: url("asset('dashboards/img/Benedicto.jpg')");
             background-position: center;
             background-size: cover;
        
    </style>

</head>

<body class="bg-gradient-primary">

    <div class="container">

        <div class="card o-hidden border-0 shadow-lg my-5">
            <div class="card-body p-0">
                <!-- Nested Row within Card Body -->
                <div class="row">
                    <div class="col-lg-5 d-none d-lg-block new-bg-register-image"></div>
                    <div class="col-lg-7">
                        <div class="p-5">
                            <div class="text-center">
                                <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1>

                                @if (!$register)
                                    <div class="alert alert-danger" role="alert">
                                        Email already exist.
                                    </div>
                                @endif
                            </div>
                            <form class="user" method="POST" action=" route('register.register') ">
                                @csrf
                                <div class="form-group">
                                    <label for="name" class="form-label">Name</label>
                                        <input type="text" class="form-control form-control-user" id="name"
                                            placeholder="Name" name="name" required>
                                    </div>
                                    <div class="form-group">
                                    <label for="email" class="form-label">Email address</label>
                                        <input type="email" class="form-control form-control-user" id="email"
                                            placeholder="Email Address" name="email" required>
                                    </div>
                                    <div class="form-group">
                                    
                                        <label for="password" class="form-label">Password</label>
                                            <input type="password" class="form-control form-control-user"
                                                id="password" placeholder="Password" name="password" required>
                                    </div>
                                    <div class="form-group">
                                  <label for="profile_image" class="form-label">Upload profile picture</label>
                                <input type="file" class="form-control-file form-control-user" id="profile_image" name="profile_image" required>
                            </div>
                                    <div class="form-group">
                                    
                                        <label for="bdate" class="form-label">Birthdate</label>
                                            <input type="date" class="form-control form-control-user"
                                                id="bdate" placeholder="Birthdate" name="bdate" required>
                                    </div>

                                    <button type="submit" class="btn btn-primary btn-user btn-block">Register</button>
                                </div>
                                <hr>
                            </form>
                            <hr>
                            <div class="text-center">
                                <a class="small" href="route('login.login')">Already have an account? Login!</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- Bootstrap core javascript-->
    <script src="asset('dashboards/vendor/jquery/jquery.min.js')"></script>
    <script src="asset('dashboards/vendor/bootstrap/js/bootstrap.bundle.min.js')"></script>

    <!-- Core plugin JavaScript-->
    <script src="asset('dashboards/vendor/jquery-easing/jquery.easing.min.js')"></script>

    <!-- Custom scripts for all pages-->
    <script src="asset('dashboards/js/sb-admin-2.min.js')"></script>

</body>

</html>

【问题讨论】:

数据库工作正常我不知道如何将它存储在laravel框架中的特定文件夹中 【参考方案1】:

你可以使用Storage:: 类来做到这一点

'profile_image' => $request->file('profile_image') ? Storage::disk('public')->put('images',$request->profile_image) : null

然后它将在数据库中存储路径以获取该文件的完整 URL,您可以再次使用 Storage::url()

喜欢

$url = \Storage::disk('public')->url($user->profile_image)

您需要像这样将enctype 添加到您的表单标签中

<form class="user" method="POST" action=" route('register.register') " enctype="multipart/form-data">

参考链接https://laravel.com/docs/8.x/filesystem

【讨论】:

表示该列不能为空 哦那你需要上传profile_image添加所需的验证 如果没有存储任何内容,我将 null 更改为默认图片,当我上传图片时它似乎没有保存在数据库中 语句有效,但是路径不存储在数据库中 这里是错误 Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_image' cannot be null (SQL: insert into users (name, emailpassworduser_typebdatecontact_noprofile_imageupdated_atcreated_at)的值(123,123 @ 123 $ 2Y $ 10 $ D84jMeksPiwOWwkIsPeYl.TUEsYPq54Oxu2xqv1bCMyYK4GlKfsPa,管理员,2021-06 -02, 123, ?, 2021-06-15 05:35:17, 2021-06-15 05:35:17)) 127.0.0.1:8000/register

以上是关于如何在 laravel 上上传文件并将其存储在目录中的主要内容,如果未能解决你的问题,请参考以下文章

laravel rest api将文件上传到服务器

如何在不写入文件的情况下压缩流并将其上传到 Azure Blob 存储?

Laravel:如何通过 API postman 上传图像并将其保存到数据库(phpmyadmin)

关于在文件系统与数据库上存储 Laravel 文件上传的问题,以及如何在需要时存储在数据库而不是文件系统中

如何使用 phalcon 上传多个图像并将其名称存储在数据库中?

Laravel如何检查文件是不是成功上传?