如何读取Node JS中的servlet响应输出stream?

用例是从服务器获取文件内容,并使用节点JS将其发送到浏览器。

细节:

在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()); } } 

获取stream并将其转换为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); } }) }); 

上面的代码抛出一个错误,说“path必须是一个没有空字节的string”。

请build议一个节点模块从java接收servlet响应输出stream并在浏览器中打开该文件。

或者build议可以从服务器发送的对象types,以便我可以将它转换成节点中的图像/ pdf文件。

你可以像下面一样把响应stream传回来,

 router.get('/openfile', function(req, res, next) { req.pipe(request.get('http://localhost:8080/getFileContent')).pipe(res); });