我的应用程序中有 pdf 文件。我需要在浏览器中显示pdf。我正在将文件作为 fileInputStream 读取,我需要在我的应用程序中的浏览器中显示 pdf。但我没有 pdf 路径,我有文件流。
请给我一些建议和例子
我使用ajax来显示pdf,我使用call_method() javascript ajax请求方法来调用showPdf操作,在showpdf操作中只是将pdf文件转换为ByteArrayOutputStream并将结果写入输出流中。但它显示了下面提到的结果。
JSP 中的结果:
%PDF-1.4 %��� 1 endstream endobj 4 0 obj >>/MediaBox[0 0 595 842]>> endobj 1 0 obj endobj 3 0 obj endobj 5 0 obj endobj 6 0 obj endobj 外部参照 0 7 0000000000 65535 f 0000000389 00000 n 0000000015 00000 n 0000000477 00000 n 0000000232 00000 n 0000000540 00000 n 000 0000585 00000 n 预告片 ]/Info 6 0 R/Size 7>> startxref 707 %%EOF
请给一些建议。
JavaScript 阿贾克斯:
call_method(); <br/>
function call_method(){
Ext.Ajax.request({
waitMsg: 'Saving changes...',
url:'test.action?method=showPdf',
params : { },
failure:function(response,options){
},
success:function(response,options){
$("#pdf_content").show();
$("#pdf_content").html(response.responseText);
$("#pdf_content").show('slow');
}
});
}
Java方法:
public String showPdf() throws IOException {
getResponse().setContentType("application/pdf");
getResponse().setHeader("Content-disposition","inline; filename=automatic_start.pdf" );
ByteArrayOutputStream baos = getByteArrayOutputStream();
getResponse().setContentLength(baos.size());
ServletOutputStream sos;
sos = getResponse().getOutputStream();
baos.writeTo(sos);
sos.flush();
return null;
}
private ByteArrayOutputStream getByteArrayOutputStream() throws IOException {
String filePath = "/homefolder/";
String folderPath=filePath+"1122/automatic_start.pdf";
File file = new File(folderPath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
ex.printStackTrace();
}
return bos;
}