Как отобразить изображение после загрузки файла проблемы с laravel - PullRequest
0 голосов
/ 02 июня 2019

После успешной загрузки файла мой show.blade, похоже, не находит мои изображения для отображения.

Я уже связал каталог, и изображение загружается прямо в нужный каталог.

post Controller

public function store(Request $request)
    {
        /**
         * Validation Rules using Validator class
         */

        $rules = [
            /*'post_id'  =>   'required|numeric',*/
            'title'    =>   'required|min:3',
            'intro'    =>   'required|min:3',
            'content'  =>   'required|min:3',
            'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'    
        ];

        $validator = Validator::make($request->all(),$rules);

        if($validator->fails()) {
            // dd('validation fail');
            return Redirect::back()
            ->withInput()
            ->with(
                [
                'notification' =>'danger',
                'message' => 'Something went wrong'
                ]
            )
            ->withErrors($validator);

        }        
        $post = new Post();
        $post->title = $request->input('title');
        $post->intro = $request->input('intro');
        $post->content = $request->input('content');
        $success = $post->save();


        /**
         * Handle image upload
         */

        if($request->hasfile('image') && $success){


            $directory = '/post-' . $post->id;

            foreach($request->file('image') as $image) {

                $name = $image->getClientOriginalName();

                $extension = $image ->getClientOriginalExtension();

                $fileName = pathinfo($name,PATHINFO_FILENAME) . '-' . time() . '.' . $extension;

                $image->storeAs($directory,$fileName,'public');

                $image = new Image();
                $image->post_id = $post->id;
                $image->filename = $fileName;
                $image->filepath = $directory;
                $image->save();
            }

                return back()->with([
                    'notification' => 'succes',
                    'message' => 'You have created a new post'
                ]);

            }

        }

Показать блейд

@extends('layout')

@section('content')

<div>
<h1 class="title">{{$post->title}}</h1>

<p> {{$post->content}} </p>
<div class="row">
@foreach($post->images as $image)
<div class="col-sm">
<img class="img-fluid" src="{{  asset($image->filepath . '/' . $image->filename) }}" alt="{{ $post->title }}">
</div>

@endforeach
</div>
</div>

<p><a href="/posts/{{ $post->id }}/edit">Edit</a></p>
@endsection

, когда я проверяю элемент, я получаю alt изображения, который является $ post-> title, ноПо какой-то причине путь кажется неверным.

Ответы [ 2 ]

0 голосов
/ 02 июня 2019

storeAs функция возвращает путь к сохраненному файлу относительно хранилища.Вам не нужно объединять это самостоятельно.Также может возникнуть проблема с косой чертой в пути.

// Store result path to the variable
$path = $image->storeAs($directory,$fileName,'public');

$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $path; // Save path returned by the storeAs
$image->save();

Используйте asset только с этим путем.

<img class="img-fluid" src="{{  asset($image->filepath) }}" alt="{{ $post->title }}">

Также проверьте конфигурацию файловой системы .public/storage должна быть символической ссылкой на storage/app/public, иначе сохраненные файлы не будут доступны из Интернета.

0 голосов
/ 02 июня 2019

попробуйте.

<img class="img-fluid" src="src="{{ asset('path/to/image/'. $image->filename) }}"" alt="{{ $post->title }}">

Я скорее одобрю его таким образом

Получите последний вставленный ID сообщения

$post_id = post->id;
$image = $request->file('image');

 if ($request->hasFile('image'))
  {
    foreach ($request->image as $img) {

            $name = $image->getClientOriginalName();

            $extension = $image->getClientOriginalExtension();

            $fileName = $name . '-' . time() . '.' . $extension;

            if (!file_exists('POST/IMAGE')) //Let check if the path doesn't exist
            {
                mkdir('POST/IMAGE', 0777 , true);// then create one with read/write permission
            }
            $image->move('POST/IMAGE',$imagename); // Save the file in this folder
        }else {
            $imagename = 'dafault.png'; // Optional: if none file selected, the use default file.
        }

            $image = new Image();
            $image->post_id = $post_idid;
            $image->filename = $fileName; 
            //$image->filepath = $directory;// You don't really need the save the file name in your DB
            $image->save();
        }

            return back()->with([
                'notification' => 'succes',
                'message' => 'You have created a new post'
            ]);

        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...