小编典典

以表单形式上传图像,使用ajax提交

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

阅读 216

收藏
2020-07-26

共1个答案

小编典典

使用FormData()该类最简单:

因此,现在您有了一个FormData对象,准备与XMLHttpRequest一起发送。并使用FormData对象附加字段

<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标头,否则,上传文件边界字符串将丢失。

2020-07-26