duanne9313 2017-04-22 07:33
浏览 181
已采纳

上传图片而不提交表单

<input type='file' name='inputfile' id='inputfile'>

I'm trying to upload an image without a form submitting - just after input file is changed:

$('#inputfile').change(function(){
    $.ajax({
        url: "pro-img-disk.php",
        type: "POST",
        data:  new FormData('#inpufile'),
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            console.log(data);
        }
    });
});

PHP

$src = $_FILES['inputfile']['tmp_name'];
$targ = "../images/".$_FILES['inputfile']['name'];
move_uploaded_file($src, $targ);

Error:
Undefined index: inputfile...

Any help?

  • 写回答

2条回答 默认 最新

  • dongyuans61046 2017-04-22 08:13
    关注

    See to the following changes:

    <input type='file' name='inputfile' id='inputfile'>
    

    Here's how you should have sent the ajax request:

    $(document).ready(function() {
        $('#inputfile').change(function(){
            var file_data = $('#inputfile').prop('files')[0];   
            var form_data = new FormData();                  
            form_data.append('file', file_data);
            $.ajax({
                url: "pro-img-disk.php",
                type: "POST",
                data: form_data,
                contentType: false,
                cache: false,
                processData:false,
                success: function(data){
                    console.log(data);
                }
            });
        });
    });
    

    And lastly, here's how you should have processed the form data:

    $src = $_FILES['file']['tmp_name'];
    $targ = "../images/".$_FILES['file']['name'];
    move_uploaded_file($src, $targ);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置