无法使用ajax上传视频

时间:2015-03-02 07:34:46

标签: jquery ajax file-upload

我正在尝试使用ajax上传视频文件。但是以下代码不起作用。当我点击上传按钮时,我收到浏览器错误消息:

 Uncaught TypeError: Illegal invocation

$('#uploadmatch').click(function(event) {
                                    var formData = new FormData($('form')[0]);
                event.preventDefault();
                $.ajax( {
                    url : 'http://localhost:8081/Football/UploadMatch',
                    data : formData,
                  //processData : false,
                    type : 'POST'
                })
                                    .done(function(message) {
                                        alert(message);
                                    })
                                    .fail(function(message){
                                        alert(message);
                                    })
});

我哪里错了?

1 个答案:

答案 0 :(得分:0)

我认为问题在于传递的数据。我已经测试了你的代码,而formData对象似乎是个问题。你错了。 FormData有一个你必须使用的附加。我找到了一个关于如何通过AJAX(http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax)上传文件的好例子,他们正在使用FormData。

以下是代码示例:

首先准备文件

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

然后是AJAX电话:

  $('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
        url: 'submit.php?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                submitForm(event, data);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
}

我希望无论如何这会帮助你。让我知道。

干杯!