4

I am trying to upload a file on change of file input but I can't get it to work because I am not so good with javascript.

I did search on google and found this: How can I upload files asynchronously?

I used it and tried to change it to how I want to use it. But I am getting the error

`Uncaught TypeError: Illegal invocation`

This is my function:

function uploadFile(formData){
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: {'formData':formData},
        //Ajax events
        success: function(html){
            alert(html);
        }
    });
}

I call the function like this:

$("input:file").change(function(){
    var file = this.files[0];
    uploadFile(file);
})

And uploadFile.php

<?php
 $formData = $_GET['formData'];
 echo $formData;
?>

I am just testing and trying to return the file in php to see if I can get it to work. But I have no idea on how I have to call it in PHP or send it with AJAX. I know how to upload it with PHP once I can retrieve the $_FILES in PHP.

4

2 回答 2

3

除了其他答案,将此添加到您的 ajax

contentType: false,
processData: false

喜欢:

var formData = new FormData();
formData.append('formData', file);
$.ajax({
    url: 'inc/ajax/uploadFile.php',  //Server script to process data
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    //Ajax events
    success: function(html){
        alert(html);
    }
});

您还应该考虑可能没有较新浏览器的人,只需输入一些错误消息,例如:

if(window.FormData === undefined){
    alert('sorry buddy, your browser\'s too old!');
    return;
}
于 2013-08-22T16:30:24.657 回答
2

您需要将数据作为FormData对象发送

function uploadFile(file){
    var formData = new FormData();
    formData.append('formData', file);
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: formData,
        //Ajax events
        success: function(html){
            alert(html);
        }
    });
}

http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata

于 2013-08-22T16:22:28.753 回答