简体   繁体   中英

Laravel 5 - upload file using ajax

I have this HTML form:

<form action="{{ route('send_form') }}" method="post" class="send_form" enctype="multipart/form-data">
        <input type="hidden" name="_token" class='token' value="{{ csrf_token() }}" />
        <input type="text" id="fullname" name="fullname" placeholder="" >
        <input type="file" id="myfile" name="myfile" />
        <button>Send</button>
</form>

I'm tring to upload the file via ajax in this why:

$(".send_form").submit(function(e) {

    e.preventDefault();
    $this = $(this);

    var $form = $( this),
        url = $form.attr( "action");

    $.ajax({
        url: url,  //Server script to process data
        type: 'POST',
        headers: { 'X-CSRF-TOKEN':$form.find('.token').val() },
        // Form data
        data: new FormData($form[0]),
        cache: false,
        contentType: 'json',
        processData: false,
        //Ajax events
        success: function( data ) {
            conosle.log('yesss');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR, textStatus, errorThrown);
        }
    });

    return false;
});

I can see that the file sent via the Request payload in the Chrome dev tools:

------WebKitFormBoundaryBXAYgtRKJjEyH6NP
Content-Disposition: form-data; name="myfile"; filename="01.png"
Content-Type: image/png

In my Laravel controller, I can't get the input in any why. The Input::all() return empty, the Request::instance()->all() is empty, also Input::get('fullname') is empty.

At the start of my controller code I have all this:

namespace App\Http\Controllers;

use App\Http\Requests;

use Request;
use Response;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redirect;
use Lang;
use Validator;
use Input;

What can I do?

Thanks

Assuming the file is actually uploaded (see below), you don't access it like a normal input. There is a special method for accessing files called file . So \\Request::instance()->file('myfile') is what you want.

Be careful when doing AJAX file uploads without a third party fallback like Blueimp. It looks like most modern browsers support it now, but IE 8 and 9 do not and IE 10 and 11 do not support responseType: 'json' . Support on mobile (Android 4.4 and below, Opera Mini) is limited as well. ( Source + some fun past bug fixing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM