Laravel uploading file using Ajax

13,620

To send files by AJAX you need to use FormData which is a class of XMLHttpRequest2, it doesn't work with IE<10.

You also need AJAX2 to show progress.

SAMPLE SUBMIT FORM WITH FILES AND PROGRESS VIA AJAX:

Here I have made an example. In this example the form sends the data and files via AJAX using FormData and show the upload progress percentage in #progress using the progress event. Obviously it is a sample and it could be changed to adapt it.

$('form').submit(function(e) { // capture submit
    e.preventDefault();
    var fd = new FormData(this); // XXX: Neex AJAX2

    // You could show a loading image for example...

    $.ajax({
      url: $(this).attr('action'),
      xhr: function() { // custom xhr (is the best)

           var xhr = new XMLHttpRequest();
           var total = 0;

           // Get the total size of files
           $.each(document.getElementById('files').files, function(i, file) {
                  total += file.size;
           });

           // Called when upload progress changes. xhr2
           xhr.upload.addEventListener("progress", function(evt) {
                  // show progress like example
                  var loaded = (evt.loaded / total).toFixed(2)*100; // percent

                  $('#progress').text('Uploading... ' + loaded + '%' );
           }, false);

           return xhr;
      },
      type: 'post',
      processData: false,
      contentType: false,
      data: fd,
      success: function(data) {
           // do something...
           alert('uploaded');
      }
    });
});

See how works!!: http://jsfiddle.net/0xnqy7du/3/

LARAVEL:

In laravel you can get the file with Input::file, move to another location and save in the database if you need it:

Input::file('photo')->move($destinationPath, $fileName);

// Sample save in the database
$image = new Image();
$image->path = $destinationPath . $fileName;
$image->name = 'Webpage logo';
$image->save();
Share:
13,620
Lihai
Author by

Lihai

Updated on June 04, 2022

Comments

  • Lihai
    Lihai almost 2 years

    I'm using the Laravel framework. I have a form of adding a new item to the database and in that form the user can also drag and drop a file. Then, a progress bar is displayed until it's completed, using Ajax for uploading the file to the server.

    Once submitting that form, I run the addItem function in a controller and I want to do/check:

    1. That the file is already hosted in the server (successful upload)
    2. If the file is hosted in the server, how do I find it? (I gave it a random name)
    3. If the user chose not to submit the form, I wish to erase that file from the server, so I won't have files that are not connected to any item on my database

    Can you suggest any ideas on how to complete these tasks?