Liam Sorsby
Liam Sorsby

Reputation: 2982

Ajax File Uploads

I have the following form:

<form method="post" enctype="multipart/form-data" id="upload"  action="upload.php">  
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>  
</form>

The following Javascript:

$(document).ready(function () {
    $("#uploadbutton").click(function () {
        var filename = $("#file").val();

        $.ajax({
            type: "POST",
            url: "upload.php",
            enctype: 'multipart/form-data',
            data: {
                file: filename
            },
            success: function (text) {
                alert("Data Uploaded: " + text);
            }
        });
    });
});

and the following PHP (as a test)

echo json_encode($_POST); //uses post to check as $_FILES returns nothing

the alert will then notify me with the response line "file: test.jpg" as you can see though this is a file name and not the actual file itself. How can i convert my file to get the actual file rather then the name of the file.

Thank you in advance.

Upvotes: 1

Views: 228

Answers (2)

user2462805
user2462805

Reputation: 1079

You still can use the "PUT" method instead of the "POST" method, it will work for all browsers except the old ones.

See : Topic

Upvotes: 1

Kevin B
Kevin B

Reputation: 95062

The syntax you are using is wrong for uploading files with ajax, you would need to pass a FormData object as the data of the request and use processData: false. However, some browsers don't support FormData, therefore you'll have to fallback to posting to a hidden iframe in those browsers.

Upvotes: 0

Related Questions