【问题标题】:How I upload an image on laravel 6?如何在 laravel 6 上上传图片?
【发布时间】:2020-07-03 10:48:55
【问题描述】:

我试图在 laravel 6 上编辑图像,但它没有前进到下一个视图,停留在表单视图上。

看过很多laravel 5.8和6的教程,怎么都搞不定

这是控制器:

 public function update(Request $request, $id)
{


    $validator = $request->validate([
       'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
       'contenido' => 'required | max:150', 
       'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
    ]);

     $image_name = time().'.'.$request->imagen->getClientOriginalExtension();
     $request->image->move(public_path('images'), $image_name);


     $datos = array(
        'titulo' => $request->titulo,
        'contenido' => $request->contenido,
        'imagen' => $image_name,
    );

    Noticia::whereId($id)->update($datos);


    return redirect('/mostrar');
}

这是 Web.php 文件:

Route::get('/actualizar/{id}', 'crearNoticiaController@update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController@edit')->name('editar');

这是表格文件:

<div class="subir-imagen">
    <form method="get" action="{{ route('actualizar', $noticia->id) }}"  enctype="multipart/form-data">
        @csrf   
        <div class="crear-titulo">
            <input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
        </div>

        <div class="crear-contenido">
            <textarea  class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
                {{$noticia->contenido}}
            </textarea>
        </div>

        <table border="2">
            <tr>
                <td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
            </tr>
        </table>



        <div class="form-group">
            <div class="col-md-6">
                <input type="file" class="form-control" name="imagen" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-6 col-md-offset-4">
                <input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
            </div>
        </div>
    </form>
</div>

感谢帮助

【问题讨论】:

    标签: php image file-upload upload laravel-6


    【解决方案1】:

    我遇到了同样的问题,但幸运的是我解决了这个问题。我在下面添加了我的解决方案,我认为这将帮助您解决这个问题

       public function updatePost(Request $request, $id)
       {
        $validatedData = $request->validate([
            'title' => 'required|unique:posts|max:25|min:4',
            'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
        ]);
    
        $data = array();
        $data['category_id'] = $request->category_id;
        $data['title'] = $request->title;
        $data['details'] = $request->details;
        $image = $request->file('image');
    
        if($image)
        {
            $image_name = hexdec(uniqid());
            $ext = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name.'.'.$ext;
            $upload_path = 'public/assets/img/';
            $image_url = $upload_path.$image_full_name;
            $success = $image->move($upload_path,$image_full_name);
            $data['image'] = $image_url;
            unlink($request->old_photo);
            $posts = DB::table('posts')->where('posts.id', $id)->update($data);
            if($posts)
            {
                return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
            }
            else
            {
                return back()->with('error', 'Posts are not inserted successfully');
            }
    
        }
        else
        {
            $data['image'] = $request->old_photo;
            $posts = DB::table('posts')->where('posts.id', $id)->update($data);
            if($posts)
            {
                return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
            }
            else
            {
                return back()->with('error', 'Posts are not inserted successfully');
            }
        }
    }
    

    edit_post.blade.php

    @extends('welcome')
    @section('content')
    <div class="container">
    <div class="row">
      <div class="col-lg-8 col-md-10 mx-auto">
        <p>
          <a href="{{ route('all.posts') }}" class="btn btn-danger">List Posts</a>
        </p>
    
        @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
        @endif
    
    <form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
        @csrf
            <div class="control-group">
                <div class="form-group floating-label-form-group controls">
                  <div>Category Name</div>
                  <label>Category ID</label>
                 <select class="form-control" name="category_id">
                   @foreach($category as $categories)
                 <option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
                    echo "selected"; ?> > {{ $categories->name }} </option>
                    @endforeach
                 </select>
                  <p class="help-block text-danger"></p>
                </div>
            </div>
    
          <div class="control-group">
            <div class="form-group floating-label-form-group controls">
              <label>Product Title</label>
            <input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
              <p class="help-block text-danger"></p>
            </div>
          </div>
    
          <div class="control-group">
            <div class="form-group floating-label-form-group controls">
              <label>Details</label>
              <textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
              <p class="help-block text-danger"></p>
            </div>
          </div>
    
          <div class="control-group">
            <div class="form-group floating-label-form-group controls">
              <label>Product Image</label>
              <input type="file" name="image" class="form-control" id="image"><br/>
    
            Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
    
            <input type="hidden" name="old_photo" value="{{ $posts->image }}">
            </div>
          </div>
    
          <br>
          <div id="success"></div>
          <div class="form-group">
            <button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
          </div>
        </form>
      </div>
    </div>
    </div>
    @endsection
    

    【讨论】:

    • 嗨,我认为问题在于验证。在我的数据库中有以下字段:id、titulo、contenido、autor、imagen、created_at 和 updated_at。使用您的代码适应我的字段,我有同样的错误,但不显示错误消息
    【解决方案2】:

    首先在您的项目控制台上运行命令:

    php artisan storage:link

    然后试试这个代码,如果返回任何错误信息告诉我khow:

    $imagen = $request->file("imagen");
    
    $extension = $imagen->extension();
    $filename = time().".".$extension;
    
    $request->file('imagen')->storeAs("public/images", $filename);
    

    最后检查您的public/images 文件夹是否存在图像文件。

    您也可以阅读有关在 laravel 6.x 官方 documentation987654321@ 中存储上传文件的信息

    【讨论】:

    • 嗨,我认为问题在于验证。在我的数据库中有以下字段:id、titulo、contenido、autor、imagen、created_at 和 updated_at。使用您的代码适应我的字段,我有同样的错误,但不显示错误消息
    【解决方案3】:

    我已经用这种方法解决了:

    在 web.php 中我放了补丁而不是 get

    Route::patch('/actualizar/{id}', 'crearNoticiaController@update')->name('actualizar');
    

    在我输入的编辑刀片中:@method('PATCH')

    这是控制器中的更新:

     public function update(Request $request, $id)
    {
    
    
        $noticia = Noticia::findOrFail($id);
    
    
        $noticia->titulo = $request->get('titulo'); 
        $noticia->contenido = $request->get('contenido');
        $noticia->imagen = $request->file('imagen');
        $validator = $request->validate([
           'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
        ]);
        $imageName = time().'.'.request()->imagen->getClientOriginalExtension();
        request()->imagen->move(public_path('images'), $imageName);
        $noticia->imagen = $imageName;
    
        $noticia->update();
    
        return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias 
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2020-06-05
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 2015-06-05
      • 2021-03-20
      相关资源
      最近更新 更多