duanne9313
duanne9313
2017-04-22 07:33

上传图片而不提交表单

已采纳
<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 dongyuans61046 4年前

    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);
    
    点赞 评论 复制链接分享
  • douyan2470 douyan2470 4年前

    Try this:

    var file_data = $('#inputfile').prop('files')[0];
    var form_data = new FormData();                     // Create a form
    form_data.append('inputfile', file_data);           // append file to form
    
    $.ajax({
            url: "pro-img-disk.php",
            type        : 'post',
            cache       : false,
            contentType : false,
            processData : false,
            data        : form_data,                         
            success     : function(response){
                alert(response);
            }
     });
    

    in php you can get the file data like:

    $_FILES['inputfile']
    
    点赞 评论 复制链接分享

为你推荐