简体   繁体   中英

Uploading an image without form submitting

<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?

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);

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']

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