【问题标题】:Laravel image uploaded not appearing in mySQL database上传的 Laravel 图像未出现在 mySQL 数据库中
【发布时间】:2020-10-20 02:13:20
【问题描述】:

我已尝试上传图片,但唯一保存的是本地文件夹中的图片。我尝试了很多方法,例如使用 save 方法,但一切都不适合我。 它在数据库表中显示为空白。当我 dd($request0>all()) 时,文件名确实出现了,但是在我 dd($funds) 之后。不知何故,图像属性消失了。

控制器

public function store(Request $request)
    {
        // Validate funds form data
        $validated = $request->validate([
            'title' => 'required|string|unique:funds|min:5|max:100',
            'content' => 'required|string|min:5|max:2000',
            'image' => 'required|image|max:2048',
        ]);

        $filename = $request->image->getClientOriginalName();
        $validated['image'] = $request->image->storeAs('images', $filename, 'public');

        // Create slug from title
        $validated['slug'] = Str::slug($validated['title'], '-');

        // Create and save funds with validated data
        $funds = Fund::create($validated);

        // Redirect the user to the created funds with a success notification
        return redirect(route('funds.index', [$funds->slug]))->with('success', 'Post created!');
    }

刀片

<form method="post" action="{{ route('funds.store') }}" enctype="multipart/form-data">

          @csrf
          @include('partials.errors')

          <div class="field">
              <label class="label">Image</label>
                 <div class="control">
                    <div class="col-md-6 mx-auto">
                        <img src="#" alt="image" id="img"
                              style="max-width:150px; display: block; margin-left: auto; margin-right: auto; padding-bottom: 10px; width: 60%;">
                           <input type="file" id="upload" name="image">
                    </div>
                 </div>
          </div>

          <div class="field">
               <div class="control">
                     <button type="submit" class="button is-link is- 
                       outlined">Publish</button>
               </div>
          </div>
</form>

【问题讨论】:

    标签: php laravel forms image


    【解决方案1】:

    除非应该存储图像的表的列是binary 数据类型,否则它永远不会出现在数据库中。

    您没有显示表的架构,所以我只能在这里猜测。如果图片正在上传并存储到您的存储目录,我建议您在上传完成后将文件路径保存到数据库(它是一个字符串)。或者,您可以只 base64_encode 图像并将其存储在该列中,以便稍后可以使用 &lt;img&gt; 元素显示它。

    【讨论】:

      【解决方案2】:

      查看this 部分官方文档。

      $path = Storage::disk('public')->put($fileName, $path);

      然后将 $path 值保存在数据库中的 imagePath 字段。

      您可以指定驱动器。一旦您在终端中运行 php artisan storage:link 命令,所有用户都可以访问 Public 。本地磁盘是私有“/storage/app/private/.....”中的所有内容。

      对于蛞蝓也可以看看这个package。如果您在特定型号中正确安装和配置它,它将自动生成 slug。

      【讨论】:

        猜你喜欢
        • 2018-05-07
        • 1970-01-01
        • 2020-01-13
        • 1970-01-01
        • 2011-06-30
        • 2016-07-21
        • 1970-01-01
        • 1970-01-01
        • 2019-09-02
        相关资源
        最近更新 更多