Laravel uploading file using Ajax

前端 未结 1 1152
死守一世寂寞
死守一世寂寞 2021-01-15 03:09

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 display

相关标签:
1条回答
  • 2021-01-15 03:20

    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();
    
    0 讨论(0)
提交回复
热议问题