使用ajax以表单形式上传图片

时间:2015-06-23 10:44:20

标签: php ajax

我的表单是使用Ajax提交的,我无法在此提交中上传图片

<form id="forms-items" name="forms-items" method="post" enctype="multipart/form-data">
<input id="uploadBtn" name="uploadimg" type="file" class="upload" />
</form    
提交代码中的

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";

输出:Please Select A File

JavaScript代码

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

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用FormData()类:

所以现在你有一个FormData对象,随时可以与XMLHttpRequest一起发送。并使用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>

并强制jQuery不为您添加Content-Type标头,否则将丢失上传文件边界字符串。