dtmm0148603 2013-12-14 07:59
浏览 152
已采纳

Ajax:如何使用FormData和jQuery发送'empty'文件并在$ _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?

  • 写回答

2条回答 默认 最新

  • dongzouqie4220 2013-12-14 08:09
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式