6
在R函數中,我使用fileName
作爲參數來讀取和處理該文件中存在的csv數據。我使用rook
包來將R與JavaScript整合。 在JavaScript中,我使用下面的代碼來獲取導入文件的文件名。使用Rook包從JavaScript傳遞文件名到R
<form id='importPfForm'>
<input type='file' name='datafile' size='20'>
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
</form>
function importPortfolioFunction(arg) {
var f = document.getElementById('importPfForm');
var fileName= f.datafile.value;
$.ajax({
type : "POST",
url : 'http://localhost:'+portNo+'/custom/Ralgotree/hBasedFileImport?fileName='+fileName,
dataType : "json",
data : '{ "method" : "hBasedFileImport", "clientId": "31d0c653-d7e5-44b6-98b5-8c084f99514a", "version": 0 }',
xhrFields: {
withCredentials: false
},
beforeSend : function(xhr) {},
success : function(data, textStatus, xmLHttpRequest){
},
error : function(xhr, ajaxOptions, thrownError) {
}
});
}
由於這種方法的只通過文件名,而不是完整的文件路徑,我不會得到R.輸出那麼什麼改變,我需要做的就是準確的輸出。 我使用下述R代碼:
s <- Rhttpd$new()
s$add(
name="Ralgotree",
app=Rook::URLMap$new(
'/hBasedFileImport' = function(env){
req <- Rook::Request$new(env)
params <- Utils$parse_query(env$QUERY_STRING);
res <- Rook::Response$new(headers = list("Content-Type"="application/json" , "Access-Control-Allow-Origin"="*"))
res$write(toJSON(hBasedFileImport(toString(params["fileName"]))))
res$finish()
}
)
)
s$start(port = 9000)
hBasedFileImport <- function(fileName){
portData <- read.csv(fileName,sep="\t")
-----
-----
}