How to send file to php via jQuery?

天大地大妈咪最大 提交于 2021-02-05 05:47:14

问题


I try send a file via jQuery to a PHP file for processing.

<form action="help-uploader.php" method="POST" class="signup" id="upform" enctype="multipart/form-data">

   <input type="text" id="title" name="title" tabindex="1" value="">
   <input id="file" type='file'" />
   <button class="submitbtn" id="submit">submit</button>
</form>

and jQuery:

$(document).ready(function(){
        $('#submit').click(function (e) {
        // custom handling here
            e.preventDefault();
            var ititle = $("#title").val();
            var ifile = $("#file").val();

            $.post("help-uploader.php",
                {
                    title: ititle,
                    file: ifile
                },function(data, status){alert("Data: " + data + "\nStatus: " + status);});
        });
    });

and **help-uploader.php**

<?php
echo $_POST['file'];
echo basename($_FILES["file"]["name"]);
?>

First ECHO prints path of file in client.

Second ECHO not prints anything.

How can I send a file to PHP via jQuery correctly?


回答1:


You need to use formdata . I am providing a example function which takes arguments ,i.e form refrence and functions callback to do stuff.This function binds event on your form submit. Try below-

function sendAjaxForm(frm,callbackbefore,callbackdone)
    {
        var form = frm;
        form.submit(function(event){
            event.preventDefault();
            var formData = new FormData(this);
            var ajaxReq=$.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: callbackbefore
                });
            ajaxReq.done(callbackdone);
        }); // submit done
    }

Now call that function as in your example

sendAjaxForm($('#upform'),function(){alert('sending');},function(data){alert("Data: " + data);})



回答2:


You need to take advantage of FormData() with use of xmlhttprequest. $.post() should not be used while performing a file upload with ajax because it doesn't use xmlhttprequest instead you should use $.ajax() or native js xmlhttprequest.

As you are using jQuery then you can do this with form submit instead:

$(document).ready(function(){
    $('#upform').submit(function(e){
      e.preventDefault();
      var fd = new FormData(document.querySelector(this));
      $.ajax({
         url: "help-uploader.php",
         type: "POST",
         data: fd,
         cache:false, // do not cache 
         processData: false,  // required
         contentType: false   // required
         success:function(data){
           console.log(data);
         },
         error:function(err){
           console.log(err);
         }
     });
   });
});


来源:https://stackoverflow.com/questions/32817326/how-to-send-file-to-php-via-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!