2013-09-26 60 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(); 

使用不同的标识和名称标签您的输入形式不是很明智无论是。