UI_Dev
UI_Dev

Reputation: 3417

How to force a Download File prompt instead of displaying it in-browser with HTML?

 <a href="sample.pdf" target="_blank">Download</a>

If I click Download button, this target blank is opening a new window.

But I need it to prompt a dialog for saving this file. How can I achieve this? enter image description here

Upvotes: 38

Views: 110288

Answers (2)

enisn
enisn

Reputation: 745

Modern browsers open known types such as jpg, pdf, etc. instead of downloading. Here is the way how I overcome this issue. Firstly fetched the entire blob with javascript and served it as a blob to user.

async function download(dataurl, fileName) {
    const response = await fetch(dataurl);
    const blob = await response.blob();

    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
}

Upvotes: 3

Kostas Rousis
Kostas Rousis

Reputation: 6068

This is something that you cannot absolutely control with HTML itself.

If the user is having a browser with PDF reading capabilities (or a plugin) and the corresponding settings to open PDF files in-browser, the PDF will open like that.

The PDF opens in a new tab simple because of your target="_blank", which has nothing to do with a download prompt.

If you are using HTML5 you can use the download attribute:

<a href="sample.pdf" download="sample.pdf">Download</a>

If you have a back-end service which you can control or you feel like fiddling with your Web Server, you can always look for setting the right Content-Disposition. See this SO question for some nice discussion on Content-Disposition.

Upvotes: 63

Related Questions