1

我有一个将图像上传到某个路径的表单。我在提交表单时没有使用它<form action="file.php">,而是使用 ajax 提交表单。数据已成功保存在数据库中,包括文件名,但根本没有上传图像。这有什么问题?我怎么能修好这个?谢谢您的帮助。这是我的代码:

表单.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>

文件.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);
           }
       } 

    });
 });

保存.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);
 ?>
4

1 回答 1

0

尝试检查 $_FILES['image_file']['tmp_name'] 或 $_FILES['cat_file']['tmp_name'] 而不是 $_POST,post 只给你参数传递的文件名,而不是实际上传的内容.

还尝试将 action='category_save.php' 添加到您的表单并改用 ajaxForm

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

为您的输入表单使用不同的 id 和 name 标签也不是很明智。

于 2013-09-26T04:22:04.193 回答