我的要求是使用HTTP Servlet将PDF数据响应到移动客户端(iPhone)。
我是按照以下方式完成的,但是我没有在客户端获得预期的输出。
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);
我遵循的方法正确吗?请指教。
谢谢。
您必须使用ServletOutputStream及其write()方法将字节写入response。