Problem uploading images to Laravel 6 with Ajax

Asked

Viewed 487 times

1

Currently I did a mini file upload project using the Asynchronous File Uploader (Ajax) and it worked. I went to try to upload images using ajax and my request is returning null, so I can not manipulate the database.

I already looked for some solutions in the forum and none solved, I saw that many were the enctype problem of the form, but I believe that mine is not.

Route:

Route::get('/', 'PostControlador@index');
Route::get('/arquivos-json', 'PostControlador@index');
Route::post('/', 'PostControlador@store');

View:

        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="arquivo" id="arquivo">
            <button type="button" class="btn btn-primary btn-save-post">Enviar</button>
        </form>

Javascript:

        $('.btn-save-post').on('click', function(){

            let formData = new FormData();
            formData.append('arquivo', $('#arquivo').val());

            $.ajax({
                url: '{{ url('/') }}',
                method: 'post',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                processData: false,
                contentType: false,
                data: formData,
                success: function(response) {
                    console.log(response);
                },
                error: function(error) {
                    console.log(error);
                }
            });

        });

Controller:

public function store(Request $request)
{
        dd ( $request->all() ); 
        // result: ["arquivo" => "C:\fakepath\2028_2229862022_a2e8c5716f_320_240_nofilter.jpg"]


        dd ( $_FILES ); 
        // result: []


        dd ( $request->file('arquivo') ); 
        // result: null


        dd ( $request->arquivo ); 
        // result: "C:\fakepath\65535_48730933186_d4b4dd1979_320_240_nofilter.jpg"
}

As you might have seen in this code, the $request->all() and $request->file Normally return the file, the global $_FILES and the $request->file('file') return null.

  • Exits the ajax and goes straight to the slider and picks up $request->file('file'); or uses js fileReader

  • @Lucasantonio thanks for commenting, but in this case it would be asynchronous, like ajax without having to refresh the page?

  • With $request->file it will not redirect to another screen and come back, with ajax tries to use fileReader which is the js library to work with files.

1 answer

2


You are passing the wrong amount on the formdata, the .val() in jQuery or .value in pure Javascript do not take the file, just take the name, so you are not uploading, you are sending the file path, the correct would be it:

formData.append('arquivo', $('#arquivo').get(0).files[0]);

This is because .get(0) takes the input and the .files[0] takes the first file (even if it is not a multiple upload, it works as Indice) so you add it directly in Formdata, then to upload you can use the Laravel functions themselves, such as the documentation example: https://laravel.com/docs/5.8/filesystem#file-uploads

public function store(Request $request)
{
    $path = $request->file('arquivo')->store('pasta_aonde_desejo_salvar');

    dd($path);
}
  • thanks for answering, unfortunately your solution did not work for me, even if I do so, it returns null when using $request->file('file'). And when I debug, it gives the error message: "Call to a Member Function store() on null", ie the store is receiving a null value, in which case it would be the image. I have done other uploads using PHP without framework and codeigniter, both using ajax and never had this kind of problem. And worse than using the superglobal $_FILES it returns empty.

  • @Igorac fixed the ajax upload, see how it turned out.

  • Sensational my young man, it worked that is a beauty. thank you very much!!

Browser other questions tagged

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