我正在尝试在我的网站上创建上载元素。我要做的是一个上传按钮,当用户从电脑中选择一个文件时,它会立即上传到服务器。
这是我的表格:
<form id="createAlert" name="createAlert" enctype="multipart/form-data" method="POST" action="createAlert.php">
<input name="title" type="text" class="input-medium" maxlength="36"></input>
<textarea name="content" rows="7" cols="90" class="input-short" style="font-family: arial; width: 80%; resize: none; height: 250px"></textarea>
<input name="push" type="checkbox"></input>
<input enctype="multipart/form-data" name="img" id="img" size="35" type="file"/>
<input class="submit-gray" type="submit" value="POST ALERT"/>
</form>
这是我的javascript代码,它将文件作为
FormData
对象到上载页(
upload.php
):
$('#img').live('change', function() {
var formData = new FormData();
formData.append('file', $('#img')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
enctype: 'multipart/form-data',
success : function(data) {
console.log(data);
alert(data);
},
cache: false,
contentType: false,
processData: false
});
});
到目前为止,一切都很好。问题在于
上传文件
接收
格式数据
. 这是它的代码(它只是一个测试版本,还没有上传文件):
<?php
print file_get_contents('php://input');
var_dump($_FILES);
var_dump($_POST);
问题是
var_dump($_FILES);
和
var_dump($_POST)
是两个空数组,而在
file_get_contents('php://input')
我得到了文件数据。
以下是输出(我剪切了上载文件内容的部分…):
------WebKitFormBoundaryw4nmFcISqYuAWQOS
Content-Disposition: form-data; name="file"; filename="Sem TÃtulo-1.png"
Content-Type: image/png
//Here is the file I uploaded...
------WebKitFormBoundaryw4nmFcISqYuAWQOS--
array(0) {
}
array(0) {
}
我在这里读了几十个问题的答案,还有许多我已经找到的解决问题的方法,但是没有一个能解决问题。
我做错什么了?为什么我只接收php://input中的文件,而不使用
$_FILES
?
谢谢您!