Laravel Загрузка изображения не сохраняется в папку c - PullRequest
0 голосов
/ 05 февраля 2020

Я борюсь с этой системой загрузки изображений. Предполагается загрузить изображение, которое будет прикреплено к сообщению (каждое сообщение имеет 1 изображение).

Кажется, все работает нормально, проблема в том, что когда я проверяю базу данных на пути к изображению, я увидеть путь к случайному временному файлу, и изображение даже не будет загружено в нужную папку в папке publi c приложения.

Проверьте логи c ниже:

PostController. php

public function store(Request $request)
{
    $post = new Post;

    $request->validate([
        'title' => 'required',
        'description' => 'required',
        'slug' => 'required',
        'message' => 'required',
        'user' => 'required',
        'post_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        if ($request->has('post_image')) {
            $image = $request->file('post_image');
            $name = Str::slug($request->input('title')).'_'.time();
            $folder = '/uploads/images/';
            $filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
            $this->uploadOne($image, $folder, 'public', $name);
            $post->post_image = Storage::url($filePath);;
        }

    Post::create($request->all());

    return \Redirect::to('admin')->with('success','Great! Post created successfully.');
}

UploadTrait. php

trait UploadTrait
{
    public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
    {
        $name = !is_null($filename) ? $filename : Str::random(25);

        $file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);

        return $file;
    }
}

Post. php (модель)

    class Post extends Model
{
    protected $fillable = [
        'title',
        'description',
        'slug',
        'message',
        'user',
        'post_image'
       ];


    public function getImageAttribute(){
        return $this->post_image;
    }

}

Create.blade. php

<form action="{{ route('blog.store') }}" method="POST" name="add_post" role="form" enctype="multipart/form-data">
{{ csrf_field() }}

<h1>New Post</h1>
<div role="separator" class="dropdown-divider"></div> 

<div class="form-row">
    <div class="form-group col-12 col-md-6">
      <label for="title">Post Title</label>
      <input type="text" autocomplete="off" class="form-control" id="title" name="title" placeholder="Your post title" required>
      <span class="text-danger">{{ $errors->first('title') }}</span>
    </div>

    <div class="form-group col-12 col-md-6">
        <label for="slug">Slug</label>
      <input type="text" autocomplete="off" class="form-control" id="slug" name="slug" placeholder="Write post slug" required>
      <span class="text-danger">{{ $errors->first('slug') }}</span>
    </div>
</div>

<div class="form-row">
    <div class="form-group col-12 col-md-12">
        <label for="description">Post Description</label>
      <textarea class="form-control" id="description" name="description" placeholder="Enter a small description for your post" required></textarea>
      <span class="text-danger">{{ $errors->first('description') }}</span>
    </div>


</div>


    <div class="badge badge-warning badge-pill">Message</div>
    <div role="separator" class="dropdown-divider"></div>

 <div class="form-row">
    <div class="form-group col-md-12">
        <textarea class="form-control" col="4" id="message" name="message"></textarea>
        <span class="text-danger">{{ $errors->first('message') }}</span>
    </div>

</div>

<input type="hidden" value="{{ Auth::user()->name }}" name="user">

<input id="post_image" type="file" class="form-control" name="post_image">



  <button type="submit" class="btn btn-warning btn-block">Create Post</button>

</form>

Спасибо за помощь!

С уважением, Тиа go

Ответы [ 3 ]

1 голос
/ 05 февраля 2020

Вы можете напрямую использовать функции, предоставляемые самой Laravel

$image_path = Storage::disk('public')->putFile('folders/inside/public', $request->file('post_image'));

Уведомление Storage::disk('public'), которое задает папку publi c.

Тогда вы можете обновить массив запросов с помощью $request['image_path'] = $image_path и сохранить его, как вы делаете в настоящее время, или вы все еще не можете использовать $post = new Post; и установить все входные данные как $post->title = $request->title;, а затем сохранить как $post->save();

0 голосов
/ 06 февраля 2020

Спасибо, Дэвид! Мне удалось исправить путь, который сохраняется в базе данных, но файлы не загружаются (хотя путь в базе данных говорит /uploads/images/something.png, когда я проверяю папку, изображение не там .. там даже нет папки для загрузки. Это метод, который я сейчас использую с вашими предложениями:

public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'description' => 'required',
            'slug' => 'required',
            'message' => 'required',
            'user' => 'required',
            'post_image' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
            ]);

            if ($request->has('post_image')) {
                $image = $request->file('post_image');
                $name = Str::slug($request->input('title')).'_'.time();
                $folder = '/uploads/images';
                $filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
                $this->uploadOne($image, $folder, 'public', $name);
                $image_path = Storage::disk('public')->putFile('uploads/images', $request->file('post_image'));
                $request['image_path'] = $image_path;

            }

            $post = new Post;
            $post->title = $request->title;
            $post->description = $request->description;
            $post->slug = $request->slug;
            $post->message = $request->message;
            $post->user = $request->user;
            $post->post_image = $request->image_path;
            $post->save();

        return \Redirect::to('admin')->with('success','Great! Post created successfully.');
    }
0 голосов
/ 05 февраля 2020

Вы не сохранили путь изображения в базе данных на созданном посте

$post = new Post; //here you have created an empty Post object
...
$post->post_image = Storage::url($filePath); //here you assigned the post_image to the empty object.

Post::create($request->all());// here you create a new POST object with the request data, which does not contain the post_image
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...