通过ajax上传文件但返回未定义的索引

时间:2014-06-22 06:23:32

标签: php ajax

当我将文件上传到Ajax时,它可以工作,但是当文件传回PHP时,它显示索引未定义。

 <html> 
 <textarea name="recipe_preparation[]"></textarea><input type="file" name="preparation_photo[]" />
 <textarea name="recipe_preparation[]"></textarea><input type="file" name="preparation_photo[]" />
</html>

这是关于我提交文件的java脚本

<script>
  var len=$("[name='preparation_photo[]']").length;
   for ( var i=0; i < len; i++ ) 
  {

  formdata.append("file", document.getElementsByName("preparation_photo[]")[i].file);

}

$.ajax({
    type : "POST",
    url : "add.php",
    data : formdata,
    processData: false,
    contentType: false,
    success : function(data){
        alert(data);
    }

});
<script>

<?php
 $target_path = "img/";
for($i=0; $i<count($_FILES['file']['name']); $i++){
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
    echo "The file has been uploaded successfully <br />";
} else{
    echo "There was an error uploading the file, please try again! <br />";
?>

1 个答案:

答案 0 :(得分:0)

您使用混合变量名称。

在HTML中,您有name="preparation_photo[]"
在PHP $_FILES['file']

切换到$_FILES['preparation_photo']