2015-11-26 47 views
-1

這裏我試圖從給定目錄中獲取所有文件名的列表。在這個URL(http://localhost:3000/dir)中,我將目錄名稱設置爲「/ usr /本地」。如何檢索給定文件夾中的文件名

我試圖從具有擴展名「.txt」的「/ usr/local」目錄中檢索所有文件。

我無法顯示文件名因以下錯誤:

跨來源請求阻止:同源策略不允許在http://localhost:3000/dir讀取遠程資源。 (原因:CORS頭「訪問控制允許來源」失蹤)我。怎麼能夠克服這個issue.Can請人幫我...

我Sample.html:

<html> 
<script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
<body> 

<div id="fileNames"></div> 


<script type="text/javascript"> 
$(window).load(function(){ 
    var fileExt = ".txt"; 

     $(document).ready(function(){ 

      $.ajax({ 

       url: 'http://localhost:3000/dir', 
       success: function (data) { 
        console.log(data); 
        $("#fileNames").html('<ul>'); 

        $(data).find("a:contains(" + fileExt + ")").each(function() { 
         $("#fileNames").append('<li>'+$(this).text()+'</li>'); 
        }); 
        $("#fileNames").append('</ul>'); 
       } 
      }); 

     }); 
}); 

</script> 
</body> 
</html> 
+0

您的網站託管在哪裏?即,您爲了打開此頁面而輸入的網址是什麼?我猜這是* not *'http:// localhost:3000/index.html' –

+0

這是網址http:// localhost:3000/loginSuccess它打開此頁面 – dev333

+0

好 - 那麼是什麼服務請求到'/dir'? IIS/Apache的?你在使用什麼服務器端技術? PHP/asp.net?如果直接在瀏覽器中輸入'/ dir'(而不是通過ajax請求),你會得到什麼?你有任何控制除了HTML以外的任何東西嗎? –

回答

0

關於在目錄列表 https://nodejs.org/api/fs.html#fs_fs_readdir_path_callback

var fs=require('fs'); 
fs.readdir('./',function(err,files){// './' - is current directory 
    console.log(files); 
}); 

關於錯誤 - 嘗試在終端curl http://localhost:3000/dir 執行有2種方式 - 服務器錯誤或客戶端錯誤。

0
** Firstly we will have to upload files using FTP on accessible location then using this code we can get the files names. #In my case i am redirecting to the file location. 

$(document).ready(function() { 
     GetDirectoryFiles(); //calling of function 
    }); 

    function GetDirectoryFiles() { //function Definition for Get All FileNames Of Directory 
     $.ajax({ 
     type: "GET", 
     url: "http://localhost:55304/TestViewsGoogleImgChanged/", 
     contentType: "application/html; charset=utf-8", 
     data: null, 
     dataType: "html", 
     success: function(data) { 
      var pagedata = $.parseHTML(data); 
      var tabledata = $.parseHTML(pagedata[9].innerHTML); 
      for (var i = 0; tabledata.length/2; i++) { 
      if (tabledata[i].textContent.indexOf('.cshtml') > 0) { 
       window.open('http://123.com/' + tabledata[i].textContent.split(".cshtml")[0], '_blank') 
      } 
      } 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert(textStatus + '-----' + errorThrown); 
     } 
     }); 
    } 
0

隨着Node.js的,你可以使用:

var fs = require('fs'); 
var files = fs.readdirSync('/usr/local/'); 

然後使用JavaScript陣列.split()功能,你可以找到和生成的文件縮小到只有.txt文件。我不確定這是否有效,因爲我自己不使用node.js,並且我從另一個stackoverflow問題中得到了這個答案,並對它進行了修改:Get list of filenames in folder with Javascript

相關問題