简体   繁体   English

使用 jquery post 和 php 上传文件

[英]upload a file using jquery post and php

trying to upload a file without using a form and using $.post to transfer the file尝试在不使用表单的情况下上传文件并使用$.post传输文件
I suppose the problem is on php side, but I'm not sure我想问题出在 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 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.您不能简单地使用 $.post 方法上传文件,并且当更改为字符串时表单数据无法发送文件。 you need to add contentType:false and processData:false, and remove this code fd = JSON.stringify(fd);您需要添加contentType:false and processData:false,并删除此代码fd = JSON.stringify(fd); Moreover, your jquery does not recognize the change since you have not addressed it properly.此外,您的 jquery 无法识别更改,因为您没有正确处理它。 it should be $('#inpfile').on('change', function() instead of just $(inpfile).on('change', function()它应该是$('#inpfile').on('change', function()而不仅仅是$(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.在 PHP 服务器端,您使用文件方法而不是发布方法检查它。 that is那是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM