Unable to download pdf blob url on Safari

后端 未结 2 1421
旧巷少年郎
旧巷少年郎 2021-01-13 08:25

Currently using FileReader to open and view a PDF that works on Chrome. However, when the pdf is opened on Safari and you click the download button, nothing happens.

2条回答
  •  有刺的猬
    2021-01-13 08:32

    After having spent an entire day working on a similar issue, I understood where the problem was so I can now share my knowledge with you.

    Basically, this kind of problems are generated when you render the Blob inside the already opened browser tab so your page url changes in something like:

    blob:http://localhost:8080/9bbeffe1-b0e8-485d-a8bd-3ae3ad9a0a51

    The wrong procedure for requiring a pdf would be something like this:

    var fileBlob = new Blob([response.data], {type: 'application/pdf'}); window.location.hfref = fileBlob;

    Why doesn't this work? Well, you can see the pdf rendered on the page so you might be fooled to thinking that your pdf is loaded fine. However, if you either try to refresh the page or download the pdf on your machine, it doesn't work.

    WTH? So, initially I was really thinking of some sort of black magic going around the browser, then I figured out the problem: The file doesn't exist but its only cache stored inside the browser. So, when you generate the blob and you redirect your current tab to point to the generated blob url, you lose the cache.

    Now everything makes sense right?

    1. You request a file on the server
    2. The browser stores the buffer inside the tab
    3. You point your page url to read the buffer
    4. You see the pdf but at the same time, you lose the buffer information

    The only think you can do, is opening the Blob url in a new tab with:

    window.open(fileBlob, '_blank');

    Problem solved.

提交回复
热议问题