How to upload to Laravel 5.7

Asked

Viewed 5,954 times

7

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Denuncia;
use Illuminate\Support\Facades\DB;

class AlunoController extends Controller
{
 public function alunoInsert(Request $request)
{
    //é bom fazer as verificações antes
    
    $extension = $request->uploaded_file->getClientOriginalExtension();
    //gera um numero unico baseado no timestamp atual
    $name = uniqid();
    //salva um nome baseado no id
    $nameFile = "{$name}.{$extension}";
    // Faz o upload:
    $upload = $request->uploaded_file->storeAs('denuncias', $nameFile);
    //envia o nome do arquivo de uma vez
    $denuncia = Denuncia::create([
        'id_usuario' => 63,
        'imagem' => $nameFile,
        ]);
        
        
        return response()->json($request);
    }

}

You’re making that mistake

{message: "Call to a Member Function getClientOriginalExtension() on null",... } Exception: "Symfony Component Debug Exception Fatalthrowableerror" file: "/var/www/html/nsi/app/Http/Controllers/Alunocontroller.php" line: 23 message: "Call to a Member Function getClientOriginalExtension() on null" trace: [{Function: "alunoInsert", class: "App Http Controllers Alunocontroller", type: "->"},...]

Line 23 $Extension = $request->uploaded_file->getClientOriginalExtension();

SOLUTION OF THE QUESTION

public function alunoInsert(Request $request)
    {
      
        
        if($request->hasFile('uploaded_file')){
            $image = $request->file('uploaded_file');
            $name = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/img_denuncia');

            $image->move($destinationPath, $name);


            $denuncia = Denuncia::create([
                'imagem' => $name
            ]);
    
        }

        return response()->json($request);
    }
  • 1

    Your input is with name uploaded_file?

  • Yeah, I’ve gone over it all, I don’t know why it’s wrong.

  • I noticed an error and I don’t know if it is, but in the form action you are sending to a different route than the one you are recovering the data. action="{{ route('rotaListarAluno') }}" Switch to: action="{{ route('rotaInsertAluno') }}"

  • Also try to check if you are sending the file by checking $request->hasFile('image')&#xA; passing in place of image the name of the field.

3 answers

8

Come on, what I’ll explain here you can find in the specializing. First, you have to define where you want to save your files, they can be in the cloud, locally. You define this through the disks in /config/filesystems.php in the following line:

'default' => env('FILESYSTEM_DRIVER', 'local'),

Instead of location you define the disk you want to use.

If you choose locally, you have to check whether this upload will be used in any view by the user. And why this? Because everything that the user sees in the application is what is inside the directory public. To resolve this you must modify from local to public on the following line:

'default' => env('FILESYSTEM_DRIVER', 'public'),

And after that run the command:

php artisan storage:link

Which creates a shortcut or direct link between the folder public and the folder storage. A tip is if you’re using Windows to run the command, make sure you run the terminal in administrator mode. Done that, on your tag form you must place the attribute enctype="multipart/form-data"which causes the files to be recognized in the request:

<form action="url-aqui" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    ...
</form>

You can then recover your file on the controller in the following way:

$arquivo = $request->file('image');

or

$arquivo = $request->image;

Also you can do checks if it is a valid file for example. Or also recover the file name, the extension, the mime type, etc. Checks:

// Se informou o arquivo, retorna um boolean
$file = $request->hasFile('image')

// Se é válido, retorna um boolean
$file = $request->file('image')->isValid()

Retrieving information:

// Retorna mime type do arquivo (Exemplo image/png)
$request->imagem->getMimeType()

// Retorna o nome original do arquivo
$request->imagem->getClientOriginalName() 

// Extensão do arquivo
$request->imagem->getClientOriginalExtension()
$request->imagem->extension()

// Tamanho do arquivo
$request->imagem->getClientSize()

Ai to upload itself you can use the function store of Request, that saves the file the way it is or storeAs, that you indicate the name of the file, the first argument is the name of the folder in which it will be saved, in case it saves on the default disk, but gives to pass the disk as well:

$upload = $request->image->store('products');
$upload = $request->image->storeAs('products', 'novonome.jpg');

I will give two solutions, because it is interesting to save a unique name to the file to avoid problems:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Denuncia;
use Illuminate\Support\Facades\DB;

class AlunoController extends Controller
{
    public function alunoInsert(Request $request)
    {
        //é bom fazer as verificações antes

        $extension = $request->image->getClientOriginalExtension();
     //salva normal a denuncia e depois que salvar o arquivo, altera o nome no banco
        $denuncia = Denuncia::create([
            'descricao' => $request->form,
            'qual_descricao' => $request->oque,
            'id_bloco' => $request->bloco,
            'id_denuncia_oque' => $request->local,
            'id_usuario' => 63,
            'imagem' => 'padrao.jpeg',
        ]);

    //salva um nome baseado no id
    $nameFile = "{$denuncia->id}.{$extension}";
    // Faz o upload:
    $upload = $request->image->storeAs('denuncias', $nameFile);
    //atualiza o nome da imagem no bd    
    $denuncia->imagem = $nameFile;
    $denuncia->save();

        return response()->json($request);
    }
}

or:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Denuncia;
use Illuminate\Support\Facades\DB;

class AlunoController extends Controller
{
    public function alunoInsert(Request $request)
    {
        //é bom fazer as verificações antes

        $extension = $request->image->getClientOriginalExtension();
        //gera um numero unico baseado no timestamp atual
        $name = uniqid();
        //salva um nome baseado no id
        $nameFile = "{$name}.{$extension}";
        // Faz o upload:
        $upload = $request->image->storeAs('denuncias', $nameFile);
        //envia o nome do arquivo de uma vez
        $denuncia = Denuncia::create([
            'descricao' => $request->form,
            'qual_descricao' => $request->oque,
            'id_bloco' => $request->bloco,
            'id_denuncia_oque' => $request->local,
            'id_usuario' => 63,
            'imagem' => $nameFile,
        ]);


        return response()->json($request);
    }
}

To recover the file in the view you can use the Asset helper and pass the image path as stated in documentation:

<img src={{asset('storage/denuncias/'. $denuncia->imagem)}}> 

I think this is the case if you have any questions see the documentation. Remembering that the examples given here were taken from documentation and of specializing.

  • Well I did the step by step but is giving error, I edited it could give a look?

6


A simple way too and..

if($request->hasFile('img')){

Checks if the file exists

            $image = $request->file('img');

Stores the file in the image variable

            $name = time().'.'.$image->getClientOriginalExtension();

Takes the name with the current team and concatenates to the file extension

            $destinationPath = public_path('/images');

Take the path destination here use as example pictures folder inside the public and use the move function to move it there ai saves the file name or the path gets the choice.

            $image->move($destinationPath, $name);

            $galery->img = $name;
            $galery->save();
        }
  • 1

    Thanks WORKED OUT HERE <3

4

According to the documentation (https://laravel.com/docs/5.7/filesystem#file-uploads), you only need to use the request file function:

$path = $request->file('imagem')->storeAs('pasta_das_imagens', 'nome_da_imagem.jpg');

Then just save the chosen path or name instead of the fixed name:

$denuncia = Denuncia::create([
    ...
    'imagem' => $path,
]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.