无法使用HTML5 PHP和Pure ajax上传图像

时间:2015-02-27 15:46:12

标签: javascript php ajax html5

我创建了一个php表单,通过textbox和1个HTML输入类型FILE接受少量值,但我的文本框数据存储到数据库,而我的Filename不存储。将图像上传到服务器目录并将其名称存储到数据库中。

的index.html

<!DOCTYPE HTML>
<html>
    <head>
        <script language="javascript" type="text/javascript" src="js/TabActions.js"></script>
    </head>
    <body>
 <form>             
 <table width="100%" border="0" align="center" >
  <input type="hidden" name="ExCategory" id="ExCategory" value="Meal">
  <tr>
    <td>Description:<br><textarea rows="4" cols="30" name= "Descr" maxlength="100"></textarea></td>
  </tr></table>
   <table width="100%" border="0" align="center" >
 <tr>
    <td> Date:</td>
    <td><input type="DATE"required name="ClaimDate" id="ClaimDate"/></td>
    <td colspan = 3><input type=file name="ClaimReceipt" id="ClaimReceipt" accept="image/jpeg,image/jpg,image/png/image/gif"></td>
  </tr>
  <tr>
   <td>Amount:</td>
    <td> <input type="number" size="5" name="ClaimAmt" id="ClaimAmt" required Placeholder="<?php echo "In ".$Currency; ?>" ></td>
</tr>
  <tr>
    <td colspan="6"  >
    <table border="0" Width="30%" height=40px >
        <tr>
            <td><input type="Button" value="Add" onclick="addFunction(ExCategory.value,Descr.value,ClaimDate.value,ClaimAmt.value,ClaimReceipt.value)"></td>
            </tr></table></td>
        </tr>        
</table>
            </div>
        </form>
    </body>
</html>

Action.js

function addFunction(ExCategory,Descr,ClaimDate,ClaimAmt,ClaimReceipt)
{
    var ajaxRequest;  // The variable that makes Ajax possible! 
    try
    {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer Browsers
        try
        {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState==4 && ajaxRequest.status==200)
        {
            document.getElementById('Res').innerHTML = ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("POST","insert.php", true);
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxRequest.send("Add=102&ExCategory="+ExCategory+"&Descr="+Descr+"&ClaimDate="+ClaimDate+"&ClaimAmt="+ClaimAmt+"&ClaimReceipt="+ClaimReceipt);
}

insert.php

<?php
session_start();
//error_reporting(E_ERROR);
$User = 'User'; 
if (isset($_POST['ClaimDate'])) 
{
    $ClaimDate = $_POST['ClaimDate'];
}
else
{
    $ClaimDate = $_POST['ClaimTo'];
}
    $ExCategory = $_POST['ExCategory'];
    if(isset($_POST['Descr']))
    {
        $ClaimClass = stripslashes($_POST['Descr']);
    }
    else
    {
        $ClaimClass = 'No description';
    }

    If(isset($_POST['ClaimFrom']) && isset($_POST['ClaimFrom']))
    {
        $ClaimFrom = $_POST['ClaimFrom'];   
        $ClaimTo = $_POST['ClaimTo'];
    }
    else
    {
        $ClaimFrom = 'Null';                 
        $ClaimTo = 'Null';
    }                   
  $ClaimAmt = $_POST['ClaimAmt'];         
if (isset($_POST['Add'])) 
{
        if (isset($_FILES['ClaimReceipt']))
        {
            if(isset($_SESSION['counter']))
            {
                $Counter = $_SESSION['counter'];
            }
            else
            {
                $Counter = 0;
            }
            $Receipt = $_FILES['ClaimReceipt'];
            $file_type= $Receipt['type'];           
            $file_path=$_FILES["ClaimReceipt"]["tmp_name"];
            $file_name = $UserID."(".$Counter.").jpeg";         
            if($file_type!= '' && ($file_type="image/jpeg" || $file_type="image/png") && $file_size < 50000)
            {
                move_uploaded_file($file_path,"uploads/".$file_name);
                $ClaimReceipt = $file_name;
                $warning = '';
                $Counter++;
                $_SESSION['counter'] = $Counter;
            }
            else
            {
                $_SESSION['counter'] = $Counter;
                $warning = "Please check format '.jpeg or .png' for attachments and its size < 500 kb";
            }
        }
        Else
        {   
            $_SESSION['counter'] = $Counter;
            $ClaimReceipt = '';                 
        }
        include('dbcon.php');
        $stmt = $dbh->prepare("CALL sp_AddExpensesEntry(?,?,?,?,?,?)"); 
        $stmt ->execute(array($User,$ExCategory,$ClaimDate,$ClaimAmt,$ClaimClass,$ClaimReceipt));
        $dbh->connection = null;
}
?>

数据库表

CREATE TABLE `MyExp` (
  `UserName` varchar(45) NOT NULL,
  `ExCategory` varchar(15) NOT NULL,
  `ClaimDate` varchar(10) NOT NULL,
  `ClaimAmt` int(11) NOT NULL,
  `ClaimDesc` varchar(100) DEFAULT NULL,
  `ClaimReceipt` varchar(20) DEFAULT NULL,
  `ClaimRowid` int(7) NOT NULL AUTO_INCREMENT,
  UNIQUE KEY `ClaimRowid_UNIQUE` (`ClaimRowid`)
)

sp_AddExpensesEntry存储过程

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_AddExpensesEntry`(
    In UserName Varchar(45),
    In Category varchar(15),
    In Claimdate varchar(10),
    In Amt int,
    In Descr varchar(100),
    In ImgURL VARCHAR(20)
)
proc_main:BEGIN

    Declare RowId int;
    If Exists(Select ClaimRowid from MyExp) then
        Set RowId = (Select ClaimRowid from MyExp Order by ClaimRowid desc limit 1) + 1;
    Else
        Set RowId = 1;
    End If;
    INSERT INTO `MyExp`
    VALUES
    (
    UserName,
    category,
    Claimdate,
    Amt,
    Descr,
    ImgURL,
    RowId
    );
    commit;
END

请帮我解决这个问题。当数据存储到没有AJAX的数据库时,文件存储机制运行良好,但为了避免页面重新加载,我试图这样做。提前谢谢。

1 个答案:

答案 0 :(得分:1)

要发布文件,您需要使用multipart / form-data而不是application / x-www-form-urlencoded。 您实际上没有使用ajax请求传递文件,这就是为什么它不会存储在任何地方。