表单提交以使用ajax上传文件以及其他字段 [英] Form submit to upload file and also other fields using ajax

查看:341
本文介绍了表单提交以使用ajax上传文件以及其他字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里测试了每个问题,并在Google上进行了很多搜索,但是没有找到有效的方法.

这是我的HTML:

<div id="createarea">
    <form id="createform" action="index/create/createcontrols.php" method="post" enctype="multipart/form-data">
      <input id="title" type="text" name="title" size="30" value="Title"><br><br>
      <input id="description" type="text" name="description" size="30" value="Description"><br><br>
      <input id="keywords" type="text" name="keywords" size="30" value="Keywords"><br><br>
      <input id="link" type="text" name="link" size="30" value="Link"><br><br>
      <input id="file" type="file" name="file"><br><br>
      <input id="submit" type="button" name='submit' value="Create" onclick="myFunction()">
    </form>
    <div id="createformresults">
    </div>
</div>  

这是JavaScript:

function myFunction() {
  $(function () {
    $('#createform').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'index/create/createcontrols.php',
        data: $('#createform').serialize(),
        success: function () {
          document.getElementById('createarea').innerHTML = "SUCCESS";
        }
      });
      e.preventDefault();
    });
  });
}

我的PHP代码:

 <?php





$db=mysql_connect('','','') or die(mysql_error());
mysql_select_db("", $db) or die(mysql_error());




$title = $_POST["title"];
$description = $_POST["description"];
$keywords = $_POST["keywords"];
$link = $_POST["link"];
        $image=$_FILES["file"]["name"];


        $allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {

    if ($_FILES["file"]["error"] > 0) {

        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";

        }

        else {

                if (file_exists("temp/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
                }

            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "temp/" . $_FILES["file"]["name"]);
            }
        }
}

else { 

    echo "Invalid file"; 

             }


            $qry="insert createcontent values('null','$title','$description','$keywords','$link','$image')";

            $res=  mysql_query($qry) or die(mysql_error());

            if(mysql_affected_rows()==1) {

                    echo "Success"; 

            }  

else {

    echo "Not Saved";                    

}



 ?> 

PHP代码运行正常,问题出在js文件中.

解决方案

我将FormData用于此任务.

以下是使用FormData的代码示例:

$(function () { //On dom ready:

$("#createform").submit(function (e) { //will be triggered on submit:

     e.preventDefault();

     if( window.FormData !== undefined ) 
     //make sure that we can use FormData ie>9, chrome > 7, opera > 12 safari >5, android > 3  gecko mobile > 2, opera mobile >12 <- wil support XHR too
     {

         var formData = new FormData($('#createform')[0]); // use "[0]" <- important
    // you can append aditional values (regular text): formData.append("be","some value");
         $.ajax({
                 url: 'index/create/createcontrols.php',  //Server script to process data
                 type: 'POST',
                 data: formData,
                 xhr: function() {  },
                 success: function(response){ $("#createformresults").text("SUCCESS"); },
                 error: function (jqXHR, textStatus, errorThrown) { $("#createformresults").text(errorThrown); },
                 //Options to tell jQuery not to process data or worry about content-type.
                 cache: false,
                 contentType: false,
                 processData: false
          });
      } else {

          //Fallback

      }

      return false;
});

});

FormData将支持多文件上传!

在属性标签中添加enctype="multipart/form-data"

注意:您可能会在服务器端页面上发现$_FILES数组为空-在这种情况下,您需要确保服务器配置允许文件上传,文件上传的大小限制足够,发布时间 足够等等....

最好的开始方法是确保允许上传文件,然后使用 小文件,以确保代码中的所有内容都可以.

I have tested every question here and have also googled alot, but did not find the something that work.

Here is my HTML:

<div id="createarea">
    <form id="createform" action="index/create/createcontrols.php" method="post" enctype="multipart/form-data">
      <input id="title" type="text" name="title" size="30" value="Title"><br><br>
      <input id="description" type="text" name="description" size="30" value="Description"><br><br>
      <input id="keywords" type="text" name="keywords" size="30" value="Keywords"><br><br>
      <input id="link" type="text" name="link" size="30" value="Link"><br><br>
      <input id="file" type="file" name="file"><br><br>
      <input id="submit" type="button" name='submit' value="Create" onclick="myFunction()">
    </form>
    <div id="createformresults">
    </div>
</div>  

And here is the javascript:

function myFunction() {
  $(function () {
    $('#createform').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'index/create/createcontrols.php',
        data: $('#createform').serialize(),
        success: function () {
          document.getElementById('createarea').innerHTML = "SUCCESS";
        }
      });
      e.preventDefault();
    });
  });
}

MY PHP CODE:

 <?php





$db=mysql_connect('','','') or die(mysql_error());
mysql_select_db("", $db) or die(mysql_error());




$title = $_POST["title"];
$description = $_POST["description"];
$keywords = $_POST["keywords"];
$link = $_POST["link"];
        $image=$_FILES["file"]["name"];


        $allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {

    if ($_FILES["file"]["error"] > 0) {

        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";

        }

        else {

                if (file_exists("temp/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
                }

            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "temp/" . $_FILES["file"]["name"]);
            }
        }
}

else { 

    echo "Invalid file"; 

             }


            $qry="insert createcontent values('null','$title','$description','$keywords','$link','$image')";

            $res=  mysql_query($qry) or die(mysql_error());

            if(mysql_affected_rows()==1) {

                    echo "Success"; 

            }  

else {

    echo "Not Saved";                    

}



 ?> 

PHP code is working fine the issue is somewhere in js file.

解决方案

I would use FormData for this task.

Here is an example of your code using FormData :

$(function () { //On dom ready:

$("#createform").submit(function (e) { //will be triggered on submit:

     e.preventDefault();

     if( window.FormData !== undefined ) 
     //make sure that we can use FormData ie>9, chrome > 7, opera > 12 safari >5, android > 3  gecko mobile > 2, opera mobile >12 <- wil support XHR too
     {

         var formData = new FormData($('#createform')[0]); // use "[0]" <- important
    // you can append aditional values (regular text): formData.append("be","some value");
         $.ajax({
                 url: 'index/create/createcontrols.php',  //Server script to process data
                 type: 'POST',
                 data: formData,
                 xhr: function() {  },
                 success: function(response){ $("#createformresults").text("SUCCESS"); },
                 error: function (jqXHR, textStatus, errorThrown) { $("#createformresults").text(errorThrown); },
                 //Options to tell jQuery not to process data or worry about content-type.
                 cache: false,
                 contentType: false,
                 processData: false
          });
      } else {

          //Fallback

      }

      return false;
});

});

FormData will support multi file upload!

Add to your Form tag the attribute: enctype="multipart/form-data"

NOTE: You may find that the $_FILES array is empty on server side page - In this case you need to make sure your server configuration allows file uploads, size limit of file upload is enough, post time is enough etc....

The best way to begin is to make sure that file uploads is allowed and then testing with very small files to be sure everything in your code is OK.

这篇关于表单提交以使用ajax上传文件以及其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆