如何使用Servlet将PDF文件数据作为响应发送? [英] How to send PDF file data as a response using Servlet?

查看:141
本文介绍了如何使用Servlet将PDF文件数据作为响应发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是使用HTTP Servlet将PDF数据响应到移动客户端(iPhone)。

My requirement is responding the PDF data to the mobile client(iPhone) using HTTP Servlet.

我是按照以下方式做的,但我没有得到预期的输出在客户端。

I did in the following way, But I am not getting expected output in the client.

    PrintWriter out = response.getWriter();

    String aInputFileName = "/Users/hcl/Desktop/Easwar/sample.pdf";
        log("Reading in binary file named : " + aInputFileName);
        File file = new File(aInputFileName);
        log("File size: " + file.length());
        byte[] result = new byte[(int)file.length()];
        System.out.println("Length : "+  result.length);
        try {
          InputStream input = null;
          try {
            int totalBytesRead = 0;
            input = new BufferedInputStream(new FileInputStream(file));
            while(totalBytesRead < result.length){
              int bytesRemaining = result.length - totalBytesRead;
              //input.read() returns -1, 0, or more :
              int bytesRead = input.read(result, totalBytesRead, bytesRemaining); 
              if (bytesRead > 0){
                totalBytesRead = totalBytesRead + bytesRead;
              }
            }
        response.setHeader("Content-Type", "application/pdf");

        out.println(result);

我遵循的方法是正确的吗?请指教。

Is the method I am following right? Please advice.

谢谢。

推荐答案

你必须使用 ServletOutputStream 及其 write()方法将字节写入响应。

You have to use ServletOutputStream and its write() method to write bytes to the response .

这篇关于如何使用Servlet将PDF文件数据作为响应发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆