2016-10-16 35 views
0

我在Java中有我的REST服務,它有一個將文件發送到客戶端(HTTP GET,/ file)的端點。我的前端客戶端在NodeJS中。我無法從REST服務下載文件。我只能將文件存儲在特定的位置,但我希望有一個下載對話框供用戶存儲文件(就像任何其他下載對話框一樣)。我的代碼的NodeJS是如下:從NodeJS中的服務器下載文件

router.get('/openFile',function(req,res){ 
    native_data_retrieval_rest_client.get("http://localhost:8080/file?fileName=presentation.pcap",function(data){ 
     var fileName="/home/files/presentation.pcap"; 
     res.download(data);//This doesnt open dialogue box 

     fs.writeFile(fileName, data, function (err) { 
      if (err) { 
       //Error handling 
      } else { 
       console.log('Done'); 
      } 
     }); 
    }); 
}); 

該文件保存靜態上的位置/home/files/presentation.pcap

我的REST服務端的響應是象下面這樣:

response.setHeader("Content-Disposition", "attachment; filename=" 
        + fileName); 
      response.setHeader("Content-Type", type); 

      reportBytes = new byte[131072];// New change 
      OutputStream os = response.getOutputStream();// New change 
      int read = 0; 
      while ((read = inputStream.read(reportBytes)) != -1) { 
       os.write(reportBytes, 0, read); 
      } 
      //System.out.println("Bytes sent" + reportBytes); 
      os.flush(); 
      os.close(); 

和我上側的NodeJS的結果就像是在它的文件內容的警告框。請參見下面的輸出:

enter image description here

任何人都可以請讓我知道我在做什麼錯在這裏。我想在用戶點擊下載按鈕時有下載對話框。點擊下載按鈕時,應該打電話給REST服務,REST服務會將文件發送到NodeJS前端,並打開一個對話框,該對話框將詢問用戶的位置。

從HTML我的電話是像下面

tr.append("td").append("button") 
.on("click", function(){ 

      openFile(); 
      }) 

function openFile(){ 
      alert("button clicked"); 

      $http.get('/openFile/').success(function(response) { 
       console.log(response.response); 
      }).error(function(error){ 
       alert(error); 
      }); 

      } 
+0

你是如何提出要求的?它是通過ajax還是隻是在您的網站上的下載鏈接。 – JoeMoe1984

+0

是的,它通過ajax ...更新我的問題與HTML部分 –

回答

1

res.download()中的數據並不需要。它需要一個文件路徑。

http://expressjs.com/en/api.html#res.download

你想成功fs.writeFile回調中調用res.download

var fileName = "presentation.pcap"; 
var filePath = "/home/files/" + fileName; 

fs.writeFile(filePath, data, function (err) { 
    if (err) { 
     //Error handling 
    } else { 
     console.log('Done'); 
     res.download(filePath, fileName, function(err) { 
      console.log('download callback called'); 
      if(err) { 
       console.log('something went wrong'); 
      } 

     }); // pass in the path to the newly created file 
    } 
}); 

更新

如果您使用的是Ajax請求,其無法下載這樣一個文件。瀏覽器使得不可能通過ajax請求進行下載。

你想要做的只是使用url下載文件到一個錨點元素。

HTML

<a class="button" href="http://localhost:3000/openFile" target="_blank">Get request</a> 

如果你需要用JavaScript做progmatically,你可以使用window.open()方法。

的Javascript

$('.button').click(function(e) { 
    e.preventDefault(); 
    window.open('http://localhost:3000/openFile', '_blank'); 
}); 

我用jQuery的在這個例子中,但我認爲這說明了需要做什麼。 window.open部分是重要的部分。

+0

你是否看到從您的終端「完成」日誌? – JoeMoe1984

+0

是的,我能夠看到日誌完成。並且該文件存儲在靜態位置。 –

+0

該代碼正在爲我工​​作。我調整了res.download參數,並添加了一個回調函數以防錯誤。當您運行該代碼時,您是否看到任何打印到控制檯的「出錯了」? – JoeMoe1984