我正在快速刺入輕量級文件上傳設施。純文本(無庫)AJAX文件上傳
關於使用jQuery將文件上傳到服務器,我想避免使用,這裏有不少答案。
我看的方式,當該文件已被使用普通的JavaScript(無JS庫)
關鍵的問題是選擇將文件上傳到服務器進行驗證:
1.爲什麼不AJAX調用工作?
2.一旦按下「上傳」按鈕,我想在服務器端驗證文件名是否相同,如果相同,則什麼都不做,如果不同,停止當前服務器處理並重新啓動 - 是有可能在PHP中做到這一點?
電流源文件的狀態都低於: HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<form id="upload_form" action="processPage.php" method="post">
<input type="file" accept=".csv" id="input_file">
<output id="file_upload"></output>
<label id="status_message"></label>
<br>
<input type="button" id="upload_to_server" value="upload" onclick="uploadFile" >
</form>
<script>
// Send file to server for validation
function handleFileSelect(e)
{
// file that was uploaded
file = e.target.files[0];
// create XMLHttpRequest object
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", "processPage.php", true);
request.setRequestHeader("X_FILENAME", file.name);
// Check status message
request.onreadystatechange = function() {
if (request.readyState == 4) {
var message;
switch (request.status) {
case 200:
message = "File validated successfully.";
break;
case 406:
message = "Error: No file selected.";
break;
default:
message = "File validation failure, check file contents.";
break;
}
var container = document.getElementById('status_message');
container.innerHTML = message;
}
else {
alert("Unexpected error: " + this.statusText + ".\nPlease try again");
}
};
request.send(file);
}
// Process file on server - send it again to server if file name changed
function uploadFile()
{
}
var output = document.getElementById('file_upload');
if (output.addEventListener) {
output.addEventListener('change', handleFileSelect, false);
} else {
output.attachEvent('change', handleFileSelect);
}
</script>
</body>
</html>
php文件:
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_SERVER['HTTP_X_FILENAME'])) {
$response_code = 406;
}
else {
// FIXME - how to distinguish between the POST from AJAX 'validate file' & 'upload file' call
$response_code = 200;
}
header('X-PHP-Response-Code: '.$response_code, true, $response_code);
?>
你使用的是jquery ajax庫嗎? – divakar 2014-10-07 03:38:41
您意識到您將事件處理程序附加到您的'
如果使用Ajax,則必須使用FormData對象發送文件,如下所示:var data = new FormData(); var xhr = new XMLHttpRequest(); data.append('file',files [i],files [i] .name); – lombardo 2014-10-07 03:51:58