Загрузите файл и сохраните его с оригинальным именем в папке хранения - PullRequest
0 голосов
/ 02 января 2019

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

Я уже перепробовал много методов и до сих пор не знаю, как решить эту проблему.

Мой продуктКонтроллер

 public function store(Request $request)
 {
    if($request->hasFile('image'))
    {
        $file = $request->file('image');
        $originalname = $file->getClientOriginalName();
        $filename =$originalname;
        $file->move('public/', $filename);
    }


    product::create([
        'name' => $request->name,
        'id_kategori' => $request->kategori,
        'quantity' => $request->quantity,
        'price' => $request->price, 
        'slug' => $request->slug,
        'image' =>  'public/'. $filename,
    ]);

    return redirect()->route('produk.index');
}

Мой Index.Blade.php

<div class="panel-body">
    <table class="table table-striped">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Nama</th>
                    <th>Kategori</th>
                    <th>Stok Barang</th>
                    <th>Harga Barang</th>
                    <th>Foto</th>
                    <th>Dibuat Pada</th>
                    <th>Diedit Pada</th>
                    <th colspan="8" style="text-align:center;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($products as $i => $products)
                    <tr>
                        <td>{{ $i+1 }}</td>
                        <td>{{ $products->name }}</td>
                        <td>{{ $products->Kategori->name }}</td>
                        <td>{{ $products->quantity }}</td>
                        <td>{{ $products->price }}</td>
                        <td><img src="{{\Illuminate\Support\Facades\Storage::url($products->image)}}"></td>
                        <td>{{ $products->created_at }}</td>
                        <td>{{ $products->updated_at }}</td>
                        <td><a class="btn btn-success" href="{{ route('produk.edit',$products->id) }}"> Edit</a></td>
                        <td>
                              <a class="btn btn-info" href="{{ route('show',$products->name) }}"> Lihat</a>
                        <td>
                            <form method="post" action="{{ route('produk.destroy',$products->id) }}">
                            {{ csrf_field() }}
                                <input type="hidden" name="_method" value="DELETE">
                                <button class="btn btn-danger" type="submit">Hapus</button>
                            </form>
                        </td>    
                    </tr>
                @endforeach
        </tbody>
    </table>
    <a href="{{ route('produk.create') }}" class="btn btn-primary">Tambah Produk</a>
</div>

Ответы [ 3 ]

0 голосов
/ 02 января 2019

Вы можете попробовать file_put_contents () сохранить файл.

file_put_contents ('/ path / to / storege, file_get_contents (' http://chart.googleapis.com/chart?chs=400x400&cht=qr&chl=Test'));

)
0 голосов
/ 03 января 2019

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

public function store(Request $request)
{   //let validate the image format;
  $this->validate($request,['image'=> 'mimes:jpeg,jpg,bmp,png',];

$file = $request->file('image'); // let request the file first
if (isset($file))
{
    $originalname = $file->getClientOriginalName();
    $file_extension = $file->getClientOriginalExtension();
    $filename = $originalname.'.'.$file_extension;

  //Now let set the path where the image will be saved.
   if (!file_exists('upload/Images')) // if this path doesn't exist
      {
        mkdir(''upload/Images', 0777 , true); // create the path
      }
      $file->move(''upload/Images',$file_name); // save the file to this path
      }else{ //optional
       $file_name = 'NoFile.jpg'; // I always set a default image that can be used if the user doesn't have an photo
      }

product::create([
    'name' => $request->name,
    'id_kategori' => $request->kategori,
    'quantity' => $request->quantity,
    'price' => $request->price, 
    'slug' => $request->slug,
    'image' => $filename,
]);

return redirect()->route('produk.index');
}

// In your index.blade.view
// To be able to display the image in your view, use the code below:
   <td>
     <img src="{{ asset('upload/Images/'.$products->image) }}" >
   </td>  

DO NOT FORGET to include enctype="multipart/form-data" in your form like below:
<form class="form-control" method="POST" action=" 
{{route('your_route')}}" enctype="multipart/form-data">
0 голосов
/ 02 января 2019

Вам не хватает расширения файла, поэтому попробуйте это:

$picture = $file->getClientOriginalName() . '.' . $file->getClientOriginalExtension();
$file->move(public_path(), $picture);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...