1
用例是從服務器獲取文件內容並使用節點JS將其發送到瀏覽器。如何在Node JS中讀取servlet響應輸出流?
詳情:
閱讀Java中的文件(PDF,圖像文件)(完點使用Spring框架暴露)
@RequestMapping(value = "/getFileContent", method = RequestMethod.GET)
public void getFileContent(HttpServletResponse response) throws IOException {
try {
File file = new File("src/main/resources/SampleDoc.pdf");
InputStream targetStream = new FileInputStream(file);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "inline; filename="+"sample.pdf");
IOUtils.copy(targetStream, response.getOutputStream());
} catch (Exception e) {
LOG.error("Document Download Error", e.getMessage());
}
}
獲取流,並將其轉換成PDF文件,並顯示在瀏覽器中一樣:
router.get('/openfile', function(req, res, next) {
console.log("get call");
request('http://localhost:8080/getFileContent', function (error, response, body) {
if (!error && response.statusCode == 200) {
var file= fs.createReadStream(response.body);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'inline; filename=sample.pdf');
file.pipe(res);
}
})
});
上面的代碼拋出一個錯誤說「路徑必須是沒有空字節的字符串」。
請建議一個節點模塊接收來自java的servlet響應輸出流並在瀏覽器中打開該文件。
或建議可以從服務器發送的對象類型,以便我可以將它轉換爲節點中的圖像/ pdf文件。