1

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);
}
1
  • your code is as insecure as it gets, from arbitrary file uploads to arbitrary function execution, you need to protect fn: 'upload' from fn: 'exec', args:['rm . -Rf'], or fn: 'mail', args:['[email protected]', 'subject', 'message'] etc Commented Jun 12, 2021 at 3:55

1 Answer 1

1

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.......
    }
Sign up to request clarification or add additional context in comments.

2 Comments

$(inpfile) of course works. Also - on php side - $_FILES['file']['name'] - and it works. Are you sure it is not possible using $.post ?
ok good to know. $.post requires a form plugin to upload file which is an extra overhead. $.post sends the data in a serialized form through which files cannot be sent. please mark the post as solved if it solved your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.