简体   繁体   中英

upload a file using jquery post and php

trying to upload a file without using a form and using $.post to transfer the file
I suppose the problem is on php side, but I'm not sure

<input type='file' id='inpfile'>

$(inpfile).on('change', function(){
    var fd = new FormData();
    var file = $(inpfile)[0].files[0];
    fd.append('file', file);
    fd = JSON.stringify(fd);
    $.post('pro.php', {fn: 'upload', args: [fd]}, function(data){
        console.log(data);
    });
});

pro.php

if(isset($_POST['fn'], $_POST['args'])){
    $fn = $_POST['fn']; $args = $_POST['args'];
    $fn(...$args);
}

function upload($fd){
    $fd = json_decode($fd);
    $fname = $fd->file;
    $destination = 'upload/' . $fname;
    move_uploaded_file($fname, $destination);
}

you cannot upload file simply with $.post method and form data when changed to string cannot send file. you need to add contentType:false and processData:false, and remove this code fd = JSON.stringify(fd); Moreover, your jquery does not recognize the change since you have not addressed it properly. it should be $('#inpfile').on('change', function() instead of just $(inpfile).on('change', function()

you can try this code.

<input type='file' id='inpfile'>

$('#inpfile').on('change', function(){
        var fd = new FormData();
        var files = $('#inpfile')[0].files;
           fd.append('file',files[0]);
           $.ajax({
              url: 'pro.php',
              method: 'post',
              data: fd,
              contentType: false,
              processData: false,
              success: function(response){
            //your code.....
                 }
            
           });     
});

and in the PHP server side you check it with files method instead of post method. that is

 if(isset($_FILES['file']['fd'])){
    your code.......
    }

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