简体   繁体   中英

How to read servlet response output stream in Node JS?

The use case is to get the file contents from the server and send it to the browser using node JS.

Details:

Read a file (PDF, image files) in Java (End point is exposed using spring framework)

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

Get the stream and convert it into pdf file and display the same in the browser:

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

The above code throws an error saying "Path must be a string without null bytes".

Please suggest a node module to receive servlet response output stream from java and open the file in the browser.

or suggest an object type that can be sent from the server so that I can convert it into an image/pdf file in node.

You can pipe the response stream back like below,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM