2017-07-19 49 views
0

我從spring控制器發送文件路徑和文件名到html頁面。 (即,從彈簧控制器向js控制器發送D:/dataStacks/myStacks/myFilename.txt)。 我想顯示文件的完整路徑以及網頁上的文件名。 請指教如何打印只返回到JS控制器FILEPATH響應對象的文件名。任何建議將有所幫助。如何在HTML頁面中只打印響應對象的一部分

JS控制器:

myApp.controller('getPathController', function ($scope, MyFilesService) { 
    $scope.getFilePathAndName = function() { 
    MyFilesService.getFiles().then(
     function (response) { 
     $scope.filePathAndName = response; // c:/dataStacks/myStacks/myFilename.txt 
     }, 
     function (errResponse) { 
     //error 
     }); 
    } 
    $scope.getFilePathAndName(); 
}); 

//service call 
myFilesService.getFiles = function() { 
    var Url = myURL + '/filesPathData/getFilePath.form'; 
    $http.get(repUrl).then(
     function (response) { 
     //return response 
     } 
     //return statement 
    } 

春天控制器:

@RequestMapping(value = "/getFilePath", method = RequestMethod.GET,produces="text/plain") 
public @ResponseBody String getFilePath1(HttpServletRequest request) throws Exception { 
    String FILEPATH = "c:/dataStacks/myStacks/myFilename.txt"; 
    File f = new File(FILEPATH); 
    //logic to deal with the file 
    return FILEPATH; 
} 

HTML:

<html> 

<body> 
    FilePath with filename : {{filePathAndName}} //logic implementation //print only the filename from above got response object 
    <h1>FileName here</h1> 
</body> 

</html> 

在我的HTML頁我想打印從響應對象所採取的文件名。 {{filePathAndName}}包含D:/dataStacks/myStacks/myFilename.txt。如何在HTML頁面中只打印文件名myFilename.txt

+0

你可以使用字符串分割功能。 – Jenny

回答

0

簡單的字符串函數/方法就足以令人欽佩:

var string = 'c:/dataStacks/myStacks/myFilename.txt'; 
var fileName = string.substring(string.lastIndexOf('/')+1); 
console.log(fileName); // myFilename.txt 
+0

2筆記:我不會命名一個變量字符串(即使我知道這只是一個模型)。此外,這返回「/ myFilename.txt」。 – Kevin

0

要提取路徑的文件名,試試這個:

var filename = "c:/dataStacks/myStacks/myFilename.txt".split("/").slice(-1)[0]; 
 
console.log(filename);

所以,你需要表達{{filePathAndName}}改爲{{filePathAndName}}.split("/").slice(-1)[0]

0

這裏一個方便的功能是lastIndexOf()。這會將/substring集合$scope.filePathAndName的最後一個實例捕獲到您要查找的最後一部分。這裏是什麼樣子的快速樣機:

var temp = "C:/folder/project/other/myFile.txt"; 
 
    var index = temp.lastIndexOf("/") + 1; 
 
    console.log(temp.substring(index));

0

在您的控制器,拆分從斜槓的路徑,並獲得數組的最後一個元素。

$scope.filePathAndName = response.split(/[/]+/).pop();