D
D
Denis Bukreev2017-10-27 20:19:47
Laravel
Denis Bukreev, 2017-10-27 20:19:47

Images are not loaded in Laravel via ajax - where am I wrong?

Loading consists of a route and a controller.
With the route, everything is simple, but here is the controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    public function upload (Request $request) {
        $path = public_path('uploads/images/');

        foreach ($request->file() as $file) {
            foreach ($file as $f) {
                $f->move($path, str_random(5).'_'.$f->getClientOriginalName());
            }
        }
        return 'Успех '.$path;
    }
}

The response to the request returns "success" and the path to the file, that is, it executes the code without errors.

The file itself is sent 100%, since the console displays it in FormData.
What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2017-10-27
@denisbookreev

Let's start with the fact that you didn't specify a file name, and Laravel has a system for working with files .
It is also not known what you have on the frontend, whether the form is configured correctly and passing csrf for ajax requests
should work like this:

//photo - имя поля
if ($request->hasFile('photo')) {
            $files = request()->file('photo');
            foreach ($files as $file) {
               //вернет имя файла, как он будет сохранен. 
                $name = $file->store('photo','public')]);               
            }
}

The files will be loaded into /storage/app/public/photo(see the first parameter $file->store, this is the folder where, the second type of storage, for everyone or another), to throw it into public for outside access, there is a command php artisan storage:link- create a symlink to this folder in the public directory.
In short, read the documentation on the file system , everything is simple there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question