使用 jquery post 和 php 上传文件

upload a file using jquery post and php

尝试在不使用表单的情况下上传文件并使用 $.post 传输文件
我想问题出在 php 方面,但我不确定

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

您不能简单地使用$.post方法上传文件,当表单数据更改为字符串时无法发送文件。您需要添加 contentType:false and processData:false, 并删除此代码 fd = JSON.stringify(fd); 此外,您的 jquery 无法识别更改,因为您没有正确处理它。应该是 $('#inpfile').on('change', function() 而不仅仅是 $(inpfile).on('change', function()

你可以试试这个代码。

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

并且在 PHP 服务器端,您使用文件方法而不是 post 方法检查它。即

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