繁体   English   中英

php Ajax文件上传,总是出现undefined index错误

[英]Php Ajax file upload, always getting undefined index error

通过ajax提交文件不起作用。 我已经按照其他帖子创建了这个,但似乎 formdata 不包含该文件,因此我总是收到未定义索引“图像”的错误

<form  enctype: 'multipart/form-data'>
<div class="add_category">
<label style="font-size:20px;">Add categories</label>
<input type="text" name="category" id="category" placeholder="Enter Here" style="border-style:solid;height:30px;">
<label style="font-size:20px;">Choose image</label>
<input type="file" id="file" name="image" style="border-style:solid;height:25px;">
<button name="add_category" type="button" onclick="addcategory()" >ADD Category</button>
</br>
</br>
</div>
</form>


function addcategory(){
//var1=document.getElementById("category").value;
var formData = new FormData();

formData.append('image', $('input[id=file]')[0].files[0]); 


$.ajax({
       url : 'performcategoryserver.php',
       type : 'POST',
       enctype: 'multipart/form-data',
       data : formData,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       success : function(data) {
             alert(data);
       }
});

}

performcategoryserver.php:

<?php
$imagename=$_FILES['image']['name'];
echo($imagename);
?>

这总是返回未定义的索引图像错误,请帮助。

改变

<form  enctype: 'multipart/form-data'> 

<form id="myform"  enctype= 'multipart/form-data'>

将您的功能更改为:

function addcategory(){
var formData = new FormData( $("#myform")[0] );


$.ajax({
       url : 'performcategoryserver.php',
       type : 'POST',
       data : formData,
       async : false,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       dataType:"json",
       success : function(data) {
             alert(data);
       }
});

}

您的表单标签首先以错误的方式打开,您可以修复它并重试吗?

<form  enctype: 'multipart/form-data'>

应该

<form method="post" enctype="multipart/form-data">

终于找到了工作代码,改成这样:

    <form id="myform"  enctype= 'multipart/form-data'>

改变了这一点:

function addcategory(){
var formData = new FormData( $("#myform")[0] );


var xhr = new XMLHttpRequest();

// Open connection
xhr.open('POST', 'performcategoryserver.php', true);

// Set up handler for when request finishes
xhr.onload = function () {
    if (xhr.status === 200) {
        //File(s) uploaded
        alert(xhr.responseText);
    } else {
        alert('An error occurred!');
    }
};

// Send data
xhr.send(formData);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM