3

I've been trying to get ajax file upload working in lavavel 4 since last two days and I'm soo out of luck right now.

my jquery block

$(document).ready(function(){

$('#basicModuleImage').change(function () {
    sendFile(this.files[0]);
});

function sendFile(file) {

  $.ajax({
    type: 'post',
    url: '/upload',
    data: file,
    enctype: 'multipart/form-data',
    success: function (data) {
            alert(data);
    },
    processData: false,
    contentType: file.type
  });
}
 });

HTML block

 <form method="post" action="">
 <input type="file" id="basicModuleImage" name="basicModuleImage" />
 </form>

LARAVEL PHP block

Route::post('upload', function(){

return Response::json(array('a'=>var_dump(Input::all()),'b'=>var_dump($_FILES)));

});

I also tried using https://github.com/LPology/Simple-Ajax-Uploader but it seems a problem with laravel.

JSON response returns a and b both null.

Naveen Gamage
  • 1,844
  • 12
  • 32
  • 51

3 Answers3

8

The key are in your ajax request. In the controller you can do whatever you want.

var form = document.forms.namedItem("yourformname"); // high importance!, here you need change "yourformname" with the name of your form
var formdata = new FormData(form); // high importance!

$.ajax({
    async: true,
    type: "POST",
    dataType: "json", // or html if you want...
    contentType: false, // high importance!
    url: '{{ action('yourController@postMethod') }}', // you need change it.
    data: formdata, // high importance!
    processData: false, // high importance!
    success: function (data) {

        //do thing with data....

    },
    timeout: 10000
});
manuelpgs
  • 1,283
  • 1
  • 14
  • 20
  • It is working like a charm. Thank You so much **herohat** – Praveen Srinivasan Jun 16 '15 at 07:32
  • @herohat thanks for `var form = document.forms.namedItem("yourformname"); // high importance!, here you need change "yourformname" with the name of your form var formdata = new FormData(form);` code, very useful sir, –  Oct 05 '15 at 05:23
  • Worked for me. Thank you. – Thang Nguyen Dec 20 '15 at 01:56
  • if you get error for route try this : `var url = '{{ route('yourcontroller') }}'; url = url.replace();` and change the url part in ajax to `url: url,` – kaann.gunerr Apr 30 '23 at 23:06
2

Actualy, you cannot send files over (basic) AJAX (XMLHttpRequest).

You eighter need to use some "iframe" uploader, or XMLHttpRequest2.
I would go for XHR2.
Here is copy-paste of portion of code I use with Laravel4, works like a charm

/**
 * Read selected files locally (HTML5 File API)
 */
var filesToUpload = null;

function handleFileSelect(event)
{
    var files = event.target.files || event.originalEvent.dataTransfer.files;
    // Itterate thru files (here I user Underscore.js function to do so).
    // Simply user 'for loop'.
    _.each(files, function(file) {
        filesToUpload.push(file);
    });
}

/**
 * Form submit
 */
function handleFormSubmit(event)
{
    event.preventDefault();

    var form = this,
        formData = new FormData(form);  // This will take all the data from current form and turn then into FormData

    // Prevent multiple submisions
    if ($(form).data('loading') === true) {
        return;
    }
    $(form).data('loading', true);

    // Add selected files to FormData which will be sent
    if (filesToUpload) {
        _.each(filesToUpload, function(file){
            formData.append('cover[]', file);
        });        
    }

    $.ajax({
        type: "POST",
        url: 'url/to/controller/action',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response)
        {
            // handle response
        },
        complete: function()
        {
            // Allow form to be submited again
            $(form).data('loading', false);
        },
        dataType: 'json'
    });
}

/**
 * Register events
 */
$('#file-input').on('change', handleFileSelect);
$('form').on('submit', handleFormSubmit);
Andreyco
  • 22,476
  • 5
  • 61
  • 65
0

Try with FormData()

$(document).ready(function () {

    $('#basicModuleImage').change(function () {
        sendFile(new FormData($('form')[0]));
    });

    function sendFile(file) {
        alert(file.type);
        $.ajax({
            type: 'post',
            url: '/upload',
            data: file,
            success: function (data) {
                alert(data);
            },
            processData: false,
            contentType: false
        });
    }
});
Spokey
  • 10,974
  • 2
  • 28
  • 44
  • thanks but still a and b both NULL. `array(2) { ["language_switch"]=> string(4) "true" ["language_id"]=> string(0) "" } array(0) { } {"a":null,"b":null}` – Naveen Gamage Mar 14 '14 at 08:12