How to fix 'The file failed to upload.' error using any validation for image upload - Laravel 5.7
Asked Answered
S

6

11

I am using Laravel 5.7

I am attempting to upload an image file and validating its upload using built in laravel validation. It keeps responding with 'The file failed to upload.'

I am using AJAX to upload this data. My form has enctype="multipart/form-data" set.

I have already figured out to include the CSRF token with the AJAX request.

I have already fixed the php.ini max_file_size issue, and the files I am testing with are far under 10MB.

If I upload a text file (as an example), and with validation set to required|image|max:10000 it will correctly prevent the file from uploading and respond with 'File must be an image.'

If I disable all validation, the file is uploaded just fine.

I cannot think of anything else I may be doing wrong. Please help as this as my project is at a halt at the moment.

Form HTML:

<form method="post" class="dropzone" action="{{ route('images') }}" enctype="multipart/form-data"
                  data-nopants-load="dropzone{'transformImage':true,'acceptedFiles-1':'image/jpg','previewsContainer':'#dropzone-previews'}">
                @method('post')
                @csrf
                <div class="dz-border">
                    <div class="background"></div>
                    <div class="border"></div>
                </div>
                <div class="dz-message margins-auto _font-size-large"><span>Drop Images here or <span class="_underline">Click</span> to Upload.</span></div>
                <div class="fallback flex-col">
                    <div class="self-center margin-bottom">
                        <input name="file" type="file" class="form-input" multiple />
                    </div>
                    <button type="submit" class="button -call">Upload</button>
                </div>
            </form>

UploadImageFormRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

use Illuminate\Support\Facades\Auth;

class UploadImageFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();//user()->can('create', Organization::class);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return ['file' => 'required|image|mimes:jpeg,bmp,png'];
    }
}

UploadImagesController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests\UploadImageFormRequest;

class UploadImagesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:user,admin');
    }

    public function store(UploadImageFormRequest $request){
    //Wont get here...
    }
}
Sling answered 21/4, 2019 at 19:48 Comment(0)
S
2

i think the multiple attribute turn it into array try remove the multiple attribute

<input name="file" type="file" class="form-input" multiple />

to this

<input name="file" type="file" class="form-input"/>

and if you want to have multiple images you should do this

<input name="file[]" type="file" class="form-input" multiple />

and your validation like this

        return [
      'file' => 'array',
      'file.*' => 'image|mimes:jpeg,bmp,png'
];
Subcontinent answered 22/4, 2019 at 8:41 Comment(1)
I am not certain if this was the final fix, but it is certainly working now AND you taught me a few things about what laravel expects for the uploads. Thank you!Sling
G
21

In my case the issue is with upload_max_filesize. So set upload_max_filesize in php.ini file fixes the issue.

upload_max_filesize = 40m
post_max_size = 50m
Glenglencoe answered 28/1, 2021 at 7:36 Comment(1)
Please, remember to restart you php-fpm service, if you're using that in your env. (e.g. sudo systemctl restart php8.1-fpm)Timber
C
4

Adding to @Rahul answer.

This might be happening because of the size upload limit on your server.

The default file size upload limit in php is limited to 2MB. When uploading files to your VPS or dedicated server via a web based content management system or document management system, you may want to increase this file size limit to accomodate larger files.

Modify Three Settings

Set the following three configuration options:

1.) upload_max_filesize - The maximum size of an uploaded file. 2.) memory_limit - This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1. 3.) post_max_size - Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.

Two Methods to Change the Settings

Depending on your level of access to the server, you can modify the settings above in two different methods.

Method #1: Edit php.ini

If you are running a (vps) virtual private server or dedicated server, your root account will have access to the php.ini file. This can be edited using the Webmin installation on your server or via SSH

a) Edit php.ini via Webmin
=======================================================================
1.) Open the Webmin control Panel
2.) In the navigation, go to "Tools > PHP Configuration"
3.) Click "Manage" next the Global PHP configuration file( URL: https://snag.gy/rH9RKD.jpg )
4.) Click "Resource Limits"
5.) Modify the settings based on the three settings above.
=======================================================================

b) Edit php.ini via SSH

Edit your php.ini file (usually stored in /etc/php.ini or /etc/php.d/cgi/php.ini or /usr/local/etc/php.ini):

Code: [Select]
# vi /etc/php.ini

memory_limit = 128M
upload_max_filesize = 20M
post_max_size = 30M

Save and close the file. Restart Apache web server: Code: [Select]

# service httpd restart

Method #2: Edit .htaccess

Edit .htaccess file in the root directory of your website. This is useful when you do not have access to the php.ini on a server. You can create the .htaccess file locally and upload it via FTP.

Append / Modify settings:

php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M

You can also use all 3 in .htaccess after everything at last line. php_value post_max_size must be more than the remaining two.

Reason why php_value post_max_size must be more than the remaining two?

  • You could be doing a post with two 30M files + more textual data, and that will cost some additional bytes.
Choosey answered 27/9, 2021 at 7:8 Comment(0)
S
2

i think the multiple attribute turn it into array try remove the multiple attribute

<input name="file" type="file" class="form-input" multiple />

to this

<input name="file" type="file" class="form-input"/>

and if you want to have multiple images you should do this

<input name="file[]" type="file" class="form-input" multiple />

and your validation like this

        return [
      'file' => 'array',
      'file.*' => 'image|mimes:jpeg,bmp,png'
];
Subcontinent answered 22/4, 2019 at 8:41 Comment(1)
I am not certain if this was the final fix, but it is certainly working now AND you taught me a few things about what laravel expects for the uploads. Thank you!Sling
D
0

sometimes you install php-fpm and must change specific ini for it. better way for find location a file is "locate" command :

$ locate php.ini

    /etc/php5/cgi/php.ini
    /etc/php5/cli/php.ini
    /etc/php5/fpm/php.ini

now if you install php-fpm must change php.ini in fpm folder.

Denicedenie answered 19/5, 2022 at 0:18 Comment(0)
D
0

This may not directly answer your question but I thought it might help somebody else looking for why their code fails when they add any validation for a file input,

In my case, using Laravel 10 with Intertia.js (Vue 3) I had forgotten to add enctype="multipart/form-data" to my form. I added that and it fixed the issue. Also don't forget that uploading files with HTML forms only works with GET and POST methods, so don't try to upload files with PATCH and PUT.

Duwalt answered 18/3, 2023 at 22:43 Comment(0)
S
0

This error had me stuck for 2 days, and was fixed by simply updating the php.ini configuration like this:

upload_max_filesize = 40m
post_max_size = 40m
Saltern answered 7/8 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.