如何通过ajax调用在新的浏览器窗口中显示来自服务器的pdf(或任何文档)

如何使用ajax调用服务器在新的浏览器窗口中呈现文档。

到目前为止,我已经完成了以下工作。

步骤1:在按钮单击并传递文件名时对服务器进行ajax调用:

$(document).ready( function(){ $('#clickme').click(function(){ $.ajax({ type:"GET", url:"App/getfile", data:{'filename':'D:\\sample.pdf'} }).done(function(msg){ var wind = window.open("_blank"); wind.document.write(msg); }); }); } ); 

第2步:我在服务器端使用spring controller:

 package my.test; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class ServeFiles { @RequestMapping(value="getfile",method=RequestMethod.GET,produces="application/pdf") public void serve(HttpServletRequest request,HttpServletResponse response) throws Exception{ InputStream is = new FileInputStream(new File(request.getParameter("filename"))); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment;filename='mypdf.pdf'"); int read; while((read=is.read())!=-1){ response.getOutputStream().write(read); } response.flushBuffer(); } } 

当pdf作为字节发送到浏览器时。 从ajax代码中,你可以看到我正在将它写入一个新窗口,如下所示

%PDF-1.4 5 0 obj <>流xڍ ڍ 0 w? Ž U 4 2 LA N “ a k > IB > x& U Ox pJ& ذ9 l + A v; [ ,Cendstream endobj 4 0 obj <> endobj 2 0 obj << /类型/ XObject / Subtype / Form / FormType 1 /PTEX.FileName(../Puzzlers.pdf)/PTEX.PageNumber 1 /PTEX.InfoDict 7 0 R / Matrix [0 -1 1 0 0 540] / BBox [0 0 540 720] /资源<< / ProcSet [/ PDF / Text / ImageC] /字体<> / XObject <> / ExtGState <> / ColorSpace <>>> /长度374 /滤波器/ FlateDecode >>流H l N @ > j& )]TDY AH EQEm“2- gBBV J Pk D , @@Hb F M @ Ȭ ѝ$ > pu TP)6Tkg |二季度,S $ B 9U # ! F ] ' p ^ \9 $ $+6)6Ι1 R y Ğ - (J!0煌c c $ e , t r ^ . 我 L ?n 7 MiK ŸNd C B ɜˌ]뿍뿍~ S } L $ Ǫma =خF “v p M e a pyBuᇈFb S ] = S u ^Aۇٴۇٴjh Ǘ @ xendstream endobj 7 0 obj <> endobj 8 0 obj <> endobj 9 0 obj <> endobj 10 0 obj << /类型/字体/子类型/类型1 / FirstChar 32 / LastChar 153 /宽度[278 259 426 556 556 1000 630 278 259 259 352 600 278 389 278 333 556 5

正如您所见,它在页面上的任何地方都显示了Unicode字符。 但我希望它像普通的pdf(或)任何其他文档(excel,doc,ppt)一样显示。

我怎样才能做到这一点?

正如Dirk Lachowski在评论中提到的那样,你所采取的方法有点问题。 pdf是一个二进制文件(不是ascii),因此它需要一个特定的内容类型,以便浏览器根据需要解释它(我看到你在Java代码中使用了“生成application / pdf”)

您的控制器方法显示正常。 因此,只需尝试通过以下操作打开新窗口上的链接:

 Click to view 

祝好运!

谢谢你帮助我。

我按照Shay的建议及其按预期工作。

我做了一个window.open("App/getfile?filepath="+String(file),"_blank"); 在我的js和它的工作伟大。 Hopefull请告诉我是否可以使用mime类型在浏览器中打开(.doc,.docx,.ppt,.pptx,.xls,.xlsx)等微软doc文件。

注意:浏览器是Internet Explorer 8.0

在新窗口/选项卡中尝试使用iframe / open文件。