简体   繁体   中英

Ajax: How to send 'empty' file using FormData and jQuery and get it in $_FILES

I have html form and want send file 'myfile' with Ajax and jQuery:

<form method="post" enctype="multipart/form-data">
    <input type="file" name="myfile" id="myfile">
</form>

My javascript code:

function getFile(fieldName){
    var itemValue = $('input[name="' + fieldName + '"]')[0].files[0];
    return itemValue;
}

function sendFile(){
    var formaData = new FormData();
    var itemName = 'myfile';
    var itemValue = getFile(itemName);
    formaData.append(itemName, itemValue);
    $.ajax({
        type: 'POST',
        data: formaData,
        processData: false,
        contentType: false,
    });
}

All works fine when file is choosen. I have in the server $_FILES global array and data in it which got via Ajax:

["myfile"]=>
    array(5) {
        ["name"]=>
        string(13) "file_name.jpg"
        ["type"]=>
        string(10) "image/jpeg"
        ["tmp_name"]=>
        string(14) "/tmp/phpefJlk3"
        ["error"]=>
        int(0)
        ["size"]=>
        int(344100)
    }

The problem when file is not choosen! When I don't choose any file and send Ajax request then I have empty $_FILES, but I have $_POST with field 'myfile' equals 'undefined'. But I need 'myfile' field in $_FILES even it is empty. I want something like:

["myfile"]=>
    array(5) {
        ["name"]=>
        string(0) ""
        ["type"]=>
        string(0) ""
        ["tmp_name"]=>
        string(0) ""
        ["error"]=>
        int(4)
        ["size"]=>
        int(0)
    }

Above is what I have in $_FILES globall array if I send empty form without Ajax. I want the same if I using Ajax. Is it posssible?

you could check for $_FILES['myfile']['error'] and $_FILES['myfile']['size'] and return an array of your choice as result. if $_FILES['myfile']['error'] is equal to zero then there is no error. you can find more details on php.net

Handling files with AJAX is not that simple. It comes up with a lot of problems due to different clients, hugh files and all that stuff. (As you can see in your "simple"-Error here =) In your case, no file is selected so there is no need to send information about "no given file". Dont produce overheads. Maybe you take a look into your controller. If the data is that different (AJAXPOST or POST) so create two PHP-Actions. One AJAX handler and one POST handler. In that case you can handle the different post-datas.

This information will help you: How can I upload files asynchronously?

You need to use Plugins like Uploadify , or Valums to make that work. Just read a bit more about AJAX and Filepost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM