I am trying to download the pdf from this url :
http://www.africau.edu/images/default/sample.pdf
I followed the example and wrote the code below.
import { saveAs } from "file-saver";
const downloadPDF = ()=>{
var FileSaver = require("file-saver");
FileSaver.saveAs(
"http://www.africau.edu/images/default/sample.pdf",
"somehthing.pdf"
);
}
However, when the downloadPDF
function is invoked on the button pressed. The file is not being saved. The pdf is simply being opened in the new tab.
The screenshot of what the pdf looks like in the new tab is shown below.
How do I save the pdf file?
Also, is this approach to get the pdf even valid in the first place or is axios.get() more preferred approach to get the file, then save the response file (response.body) via FileSaver.saveAs()
If the question is unclear, please let me know in the comment before flagging - I will make the necessary update. Thank you
CodePudding user response:
seems like the FileSaver
does not help.
However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatiblity.
as far as I know, there are 2 ways to download file in browser.
server returns a response with header
Content-Disposition
with valueattachment
or headerContent-Type
with valueapplication/octet-stream
. Browser will promote the SaveDialog and handle this download for you. This is preferred way to download but this requires you to have control over the server.you just use
ajax
oraxios
toget
the data of any file at anywhere. then you create a dummy link to download (like this one). then browser will promote for SaveDialog and then save file to disk. This is just fine for small file but not for large files because you have to store entire file in memory before saving it to local disk.
I think option 2 is appropriate for you.
Example here. In this example, I place a file named abc.json
in public folder. Note that the server must enable cors for your website origin. otherwise, there's no way for you to access that file in javascript code.
CodePudding user response:
This should work for forcing a local download. Create a fake link and click it via javascript
function browserDownloadFile(url) {
const link = document.createElement('a');
link.setAttribute('href', url);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}