Laravel 中的 AJAX 文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22399322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:11:21  来源:igfitidea点击:

AJAX file upload in laravel

phpjqueryajaxlaravellaravel-4

提问by Naveen Gamage

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.

自前两天以来,我一直试图让 ajax 文件上传在 lavavel 4 中工作,但我现在运气不好。

my jquery block

我的 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 block

HTML 块

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

LARAVEL PHP block

LARAVEL PHP 块

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-Uploaderbut it seems a problem with laravel.

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

JSON response returns a and b both null.

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

回答by herohat

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

关键在您的 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
});

回答by Andreyco

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

实际上,您不能通过(基本)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

您需要使用一些“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);

回答by Spokey

Try with FormData()

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