使用JavaScript XMLHTTPRequest在浏览器中打开PDF

发布于 2025-02-04 06:04:57 字数 1077 浏览 3 评论 0原文

因此,我环顾四周,并尝试查看浏览器中的PDF打开Blob的最佳方法。我能找到的最接近的Stackoverflow问题是: xmlhttprequest在browser中打开pdf 但这是11岁。目前,我有一个看起来像这样的程序:

var xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:8080/api/download', true);
  xhr.responseType = 'blob';
  
  xhr.onload = function(e) {
    if (this.status == 200) {
      // Note: .response instead of .responseText
      var blob = new Blob([this.response], {type: 'application/pdf'}),
          url = URL.createObjectURL(blob);
          window.open(url, '_blank');     
    }
  };
  xhr.send();

现在再次发行,它在Chrome浏览器(FYI:版本102.0.5005.61(官方构建)(ARM64))中使用UUID打开。因此,新标签的URL看起来像这样:

blob:http:// localhost:3000/f7c5571a-bf59-45d1-99ea-e495fe859008

现在,当我单击下载图标时。 File Explorer在其中打开了UUID,我无法在Windows中下载它。当我尝试时,说网络错误。

问题:在浏览器中仅显示PDF的最佳方法是什么。 如果它们不工作。

在删除下载图标时, 这很好,但是我不想下载文件,只需在浏览器上查看即可。我还尝试了内容内联和附件。不起作用。结果相同。

多谢!

So I've looking around a lot and try to see best way to open blob as pdf in browser. Closest stackoverflow question i was able to find was this one:
XMLHttpRequest to open PDF in browser
but this is 11 years old. Currently I have a program that looks like this:

var xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:8080/api/download', true);
  xhr.responseType = 'blob';
  
  xhr.onload = function(e) {
    if (this.status == 200) {
      // Note: .response instead of .responseText
      var blob = new Blob([this.response], {type: 'application/pdf'}),
          url = URL.createObjectURL(blob);
          window.open(url, '_blank');     
    }
  };
  xhr.send();

Now again Issue here is that it opens in chrome browser ( FYI: Version 102.0.5005.61 (Official Build) (arm64)) with a UUID. So url of new tab looks something like this:

blob:http://localhost:3000/f7c5571a-bf59-45d1-99ea-e495fe859008

Now when I click on download icon. File explorer opens up with UUID in it and I cannot download it in windows. When I try it says network error.

Question: What is best possible way to display just pdf in browser. While removing downloading icons if they are not going to work.

Oh i have also tried creating the link and then doing link.download = fileName; That works perfectly fine but I am not looking to download file just view it on browser. I have also tried content-disposition inline and attachment. Does not work. Result is same.

Thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲欢浪云 2025-02-11 06:04:57

我能够通过提供服务来解决这个问题。使用Get Call Chrome浏览器的行为。 Chrome lools在内容分配标头处并下载或在新文件中打开PDF。

I was able to solve this by having service as a GET not POST. With GET call chrome browser behaves as it should. Chrome lools at content-disposition header and downloads or opens pdf in new file accordingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文