2013-09-26 58 views
1

我有一個表單將圖像上傳到某個路徑。在提交表單時我沒有使用這個<form action="file.php">,而是我使用了ajax來提交表單。數據成功保存在包括文件名的數據庫中,但圖像根本沒有上傳。這有什麼問題?我怎樣才能解決這個問題?謝謝您的幫助。這裏是我的代碼:PHP基於ajax的客戶端文件上傳不起作用

form.php的

<form method="post" name="new_category" id="product_category" enctype="multipart/form-data"> 
<ul class="add_prod"> 
<li>Category Title:<input type="text" name="category[title]" id="cat_title" value="" placeholder="Title" /> </li> 
<li>Category Description:<textarea rows="4" cols="40" name="category[description]"></textarea></li> 
<li>Category Image:<input type="file" name="image_file" id="cat_image" /></li> 
</ul> 
</form> 

file.js

$("#product_category").submit(function(){ 

    event.preventDefault(); 

    var data_category = $(this).serialize(); 
    var image = $("#cat_image").val(); 
    $.ajax({ 
     type: "post", 
     url: "../wp-content/plugins/product_form/category_save.php", 
     dataType: "json", 
     data:data_category + "&image_file=" +image, 
     success: function(data){ 
      if(data.notify == "Success"){ 
       console.log(data.notify); 
      } 
      else{ 
       console.log(data.notify); 
      } 
     } 

    }); 
}); 

Save.php

<?php 
//establish connection 
$con = mysqli_connect("localhost","root","","database"); 
//on connection failure, throw an error 
if(!$con) { 
die('Could not connect: '.mysql_error()); 
} 

$folder = "../Dropbox/estacio/wp-content/plugins/product_form/img/"; 

if (is_uploaded_file($_POST['image_file']['tmp_name'])) { 
if (move_uploaded_file($_POST['image_file']['tmp_name'], $folder.$_POST['image_file']['name'])) { 
    echo "File uploaded"; 
    } else { 
    echo "File not moved to destination folder. Check permissions"; 
    } 
    } else { 
    echo "File is not uploaded."; 
} 



    //get the form elements and store them in variables 
    $category_values = $_POST["category"]; 
    $image_url = basename($_POST["image_file"]); 
    $image_field = "image_url"; 
    $data = array(); 

    //unset($view_all_info['Password2']); 
    foreach($category_values as $field => $val){ 
    $data[] = "`".$field."` = '".$val."'"; 
    } 

    array_push($data,"`".$image_field."` = '".$image_url."'"); 

    $sql = "INSERT INTO wp_product_category SET ".implode(',', $data); 
    $ret = mysqli_query($con,$sql); 

    if($ret){ 
    $notification="Success"; 
    } 
else{ 
    $notification="Failed"; 
    } 

    echo json_encode(array('notify'=>$notification)); 

    mysqli_close($con); 
?> 
+0

您需要使用XHR2,它只能在最棒的瀏覽器和最新的IE中使用。 – Musa

+0

你傳遞的文件名在你的ajax中,但是我相當肯定你仍然需要訪問保存在'$ _FILES'超全局而不是'$ _POST'中的文件數據。 – Jeemusu

+0

你能告訴我你的代碼嗎?感謝您的幫助 – Eli

回答

0

嘗試檢查$ _FILES [ 'IMAGE_FILE'] [」 tmp_name']或者$ _FILES ['cat_file'] ['tmp_name']而不是$ _POST,post只會給你參數傳遞的文件名,而不是實際的up加載的內容。

也嘗試加入行動=「category_save.php」到您的形式和使用給ajaxForm代替

$("#product_category").ajaxForm(
{ 
dataType:'json', 
success:function(json){ 
    console.log('success'); 
} 
}).submit(); 

使用不同的標識和名稱標籤您的輸入形式不是很明智無論是。