【问题标题】:AJAX file upload in laravel在 laravel 中上传 AJAX 文件
【发布时间】:2014-04-19 09:49:10
【问题描述】:

自从过去两天以来,我一直在尝试让 ajax 文件上传在 lavavel 4 中工作,但我现在很不走运。

我的 jquery 块

$(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 块

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

LARAVEL PHP 块

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

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

});

我也尝试过使用https://github.com/LPology/Simple-Ajax-Uploader,但这似乎是 laravel 的问题。

JSON 响应返回 a 和 b 均为 null。

【问题讨论】:

    标签: php jquery ajax laravel laravel-4


    【解决方案1】:

    密钥在您的 ajax 请求中。在控制器中你可以做任何你想做的事情。

    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
    });
    

    【讨论】:

    • 它就像一个魅力。非常感谢herohat
    • @herohat 感谢var form = document.forms.namedItem("yourformname"); // high importance!, here you need change "yourformname" with the name of your form var formdata = new FormData(form); 代码,非常有用的先生,
    • 为我工作。谢谢。
    【解决方案2】:

    实际上,您不能通过(基本)AJAX (XMLHttpRequest) 发送文件。

    你需要使用一些“iframe”上传器,或者 XMLHttpRequest2。
    我会选择 XHR2。
    这是我在 Laravel4 中使用的部分代码的复制粘贴,就像一个魅力

    /**
     * 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);
    

    【讨论】:

      【解决方案3】:

      试试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
              });
          }
      });
      

      【讨论】:

      • 谢谢,但 a 和 b 仍然为 NULL。 array(2) { ["language_switch"]=&gt; string(4) "true" ["language_id"]=&gt; string(0) "" } array(0) { } {"a":null,"b":null}
      猜你喜欢
      • 2017-08-02
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      相关资源
      最近更新 更多