[英]watch local directory for new files in javascript/html5
正如標題所說,是否可以監控真實文件系統中的本地目錄(而不是html5沙箱)? 我想寫一個自動照片上傳器,尋找新照片並上傳它們。
使用Javascript可能重復本地文件訪問 。
我的理解是你不能直接通過Web瀏覽器訪問本地文件系統,你必須使用像表單輸入標簽這樣的中介或拖放。
如果您要使用操作系統的javascript解釋器或V8之類的東西,您可能能夠訪問文件系統。 Chrome中可能還有一些實驗性的javascript api,你可以在Chrome標記頁面上查找,如果這是您選擇的瀏覽器。 這一切都取決於你是否在做個人項目或網絡的東西。
否則,另一種腳本語言(如PHP,Ruby或Python)將更適合您的需求。
您可以設置Javascript Timing事件。 即:使用setInterval()
方法。
另一方面,您可以創建一個按鈕來觸發onClick event
或任何其他事件,以執行以下代碼。
注意:
如果您設置了間隔,請確保在再次發送之前收到了請求。
為實現此目的,您需要檢查XML HTTP Request的readyState是否等於4,如下所示:
xmlhttp.readyState == 4
注意:
這是用於發送請求,解析響應並將其放入Javascript數組中:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "check_dirs.php", true);
xmlhttp.send();
fileArray = new Array();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlDoc = xmlhttp.responseXML;
fileList = xmlDoc.getElementsByTagName("filesChanged");
while (fileArray.length > 0)
// clean the whole array.
// we want to store the newly generated file list
{
fileArray.pop();
}
for (i = 0; i < fileList.length; i++)
{
fileArray[fileArray.length] = fileList[i].childNodes[0].nodeValue;
}
}
}
此外,您需要編寫一個小PHP script
來檢查自定義目錄中是否存在比給定日期更新的文件,這些文件可以在請求中發送,然后發回XML響應 ,如下所示:
<?php
(...) // check dir. output $files contain the xml nodes for the files to send
// mockup below
// Get our XML. You can declare it here or even load a file.
$xml_builder = '<?xml version="1.0" encoding="utf-8"?>';
$xml_builder .= $files;
// We send XML via CURL using POST with a http header of text/xml.
$ch = curl_init('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.hello..co.uk');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ch_result = curl_exec($ch);
curl_close($ch);
/*
echo $ch_result;
*/
?>
以下是一些用於檢查目錄和構建XML響應的模型函數:
<?php
function analizeDir($dir)
{
if (is_dir($dir))
{
$dir_resource = opendir($dir);
while (false !== ($res = readdir($dir_resource)))
{
if ($res != "." && $res != ".." && $res != "old")
{
if (is_dir($dir . "\\" . $res)) // this is a subforder
{
analizeDir($dir . "\\" . $res);
} else { // this is a file
checkFile($dir . "\\" . $res);
}
}
}
}
}
function checkFile($file)
{
$today = date("Y-m-d H:i:s");
// if the difference in days between today
// and the date of the file is more than 10 days,
// print it in the response
if (date_diff(datemtime($file), $today) > 10)
{
$files .= "<filesChanged>" . $file . "</filesChanged>";
}
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.