Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

php - upload image in form submit with ajax

I have form submited with Ajax I can't upload image in this submit

<form id="forms-items" name="forms-items" method="post" enctype="multipart/form-data">
<input id="uploadBtn" name="uploadimg" type="file" class="upload" />
</form    

in submit code

if($_FILES['uploadimg']['size']>0)
{
    $ftype=$_FILES["uploadimg"]["type"];
    if(move_uploaded_file($_FILES['uploadimg']['tmp_name'], $target_path)) 
    {
        $default=1;
        $mesg="File Uploaded Successfully";
    }
    else
        $mesg="File Uploading Failed!!";
    else
        $mesg="Please Select A File";

The output: Please Select A File

JavaScript code

$("#forms-items").submit(function()
{   
    $.ajax({
        url: "ajax/submitform.php",
        type: "POST",
        data: $("#forms-items").serialize(),
        success: function(response) {
            alert(response);
        }
    }); 
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it’s easiest to use the FormData() class:

So now you have a FormData object, ready to be sent along with the XMLHttpRequest. and append fields with FormData Object

<script type="text/javascript">
           $(document).ready(function () {
               var form = $('#forms-items'); //valid form selector
               form.on('submit', function (c) {
                   c.preventDefault();

                   var data = new FormData();
                   $.each($(':input', form ), function(i, fileds){
                       data.append($(fileds).attr('name'), $(fileds).val());
                   });
                   $.each($('input[type=file]',form )[0].files, function (i, file) {
                       data.append(file.name, file);
                   });
                   $.ajax({
                       url: 'ajax/submitform.php',
                       data: data,
                       cache: false,
                       contentType: false,
                       processData: false,
                       type: 'POST',
                       success: function (c) {
                            //code here if you want to show any success message
                           alert(response);
                       }
                   });
                   return false;
               });
           })
</script>

and forcing jQuery not to add a Content-Type header for you, otherwise, the upload file boundary string will be missing from it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...