vitto
vitto

Reputation: 19476

Checking file props before upload

I am practicing with PHP and AJAX but I have some problems!

I'm trying to get the filename, type, size from a jQuery alert after select an image to upload, but I keep getting an empty string.

<form action="upload_file.php" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="my_file" />
    <input type="submit" name="submit" value="Submit" />
</form>

This form includes a JS file that has an ajax script that asks to a php page the filename of the posted file, but it doesn't work. Do I need to upload the file before I try to get this data?

The JS file:

$("input").change (function () {
    $.post("preview_uploader.php", { action:"get_size" }, function (data) {
        alert (data);
    });
});

The PHP file preview_uploader.php:

<?php
    if ($_POST["action"] == "get_test") print "text string test works!";
    if ($_POST["action"] == "get_name") print $_FILES["my_file"]["name"];
    if ($_POST["action"] == "get_size") print $_FILES["my_file"]["size"];
    if ($_POST["action"] == "get_type") print $_FILES["my_file"]["type"];
?>

It works if i make a test with action:"get_test" with php page but it doesn't work with $_FILES["my_file"]["name"] or $_FILES["my_file"]["type"] etc...

Can someone help me find where I am wrong?

Thanks!

Upvotes: 1

Views: 1217

Answers (2)

Peter
Peter

Reputation: 767

You can actually get the size with jQuery. See the answer to this questions:

How to check file input size with jQuery?

You can use the method given to get the name, size, and type. General belief is that its not possible. You can't always believe everything you hear...

Upvotes: 1

Doug Neiner
Doug Neiner

Reputation: 66191

Your JS script is sending a separate request to the server and so your PHP is unaware of the file, and $_FILES["my_file"] is not a valid index.

You do not need to go to the server to get the file name, simply use this to get the file name:

$("input[type=file]").val();

I believe it brings back the path as well, so you will need to strip the path off to get the filename.

If you are trying to get all the additional details (filesize, etc) you will either need to upload the file first (which defeats what you are trying to do) or use a Flash + JavaScript combination like these solutions:

Upvotes: 2

Related Questions