file_upload_parser.php無法使用PHP和Javascript
<?php
var_dump($_FILES);
if (isset($_FILES['file'])) {
var_dump($_FILES);
$fileName = $_FILES["file"]["name"];
$fileTmpLoc = $_FILES["file"]["tmp_name"];
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
$fileErrorMsg = $_FILES["file"]["error"];
if (!$fileTmpLoc) {
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
} else {
echo "File not found.";
}
?>
Javascript功能來上傳文件:
function _(el){
return document.getElementById(el);
}
function uploadFile() {
var file = _("file").files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded/event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
形式:
<form name="uploads" action="file_upload_parser.php" enctype="multipart/form-data" method="post" class="form-horizontal" id="_uploads">
<div id="container">
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Uploads</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-sm-2 control-label" for="_file"> </label>
<div class="col-sm-10">
<input type="file" name="file" id="file">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="_button"> </label>
<div class="col-sm-10">
<button type="button" name="button" value="Upload File" class="btn btn-success" onclick="uploadFile()" id="_button">Upload File</button>
</div>
</div>
這就是我得到:
我檢查了我的php.ini文件以驗證文件上傳已打開,並且文件大小的限制足夠高,但每次運行此代碼時,$ _FILE總是空的。 FormData抓取文件並正確地將名稱,大小和類型輸出到控制檯,但與file_upload_parser.php的通信正在進行。
我也確定文件夾&文件權限設置爲完全訪問。
任何想法?
你見過這個http://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php – j08691
只是爲了檢查,你嘗試上傳文件沒有JS,只是正常提交表單? – Pango
@ j08691雅在發佈之前我檢查了一下。 – Josh