Instead of downloading, files are opening in browser
Solution 1
As per JavaScript/jQuery to download file via POST with JSON data construct a blob and use that to return the file reference for the link.
This will inform the browser of your intent in a standards compliance manner.
example ...
$.get(/*...*/,function (result)
{
var blob=new Blob([result]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.txt";
link.click();
});
Solution 2
Solution
Content-Disposition attachment seems to work for me:
self.set_header("Content-Type", "application/json")
self.set_header("Content-Disposition", 'attachment; filename=learned_data.json')
Workaround
application/octet-stream
I had something similar happening to me with a JSON, for me on the server side I was setting the header to self.set_header("Content-Type", "application/json") however when i changed it to:
self.set_header("Content-Type", "application/octet-stream")
It automatically downloaded it.
Also know that in order for the file to still keep the .json suffix you will need to it on filename header:
self.set_header("Content-Disposition", 'filename=learned_data.json')
Amit Chauhan
Updated on July 20, 2022Comments
-
Amit Chauhan almost 2 years
My Pdf file is stored in google bucket, and i have a link let say https://storage.googleapis.com/bucketName/xyz.pdf. To download this file i am doing this,
<a href="https://storage.googleapis.com/bucketName/xyz.pdf" download> Download This File </a>
But when i click on this anchor tag, instead of downloading this file browser open this file in same tab even i try to download the file via javascript and was using this code .
var link = document.createElement("a"); link.download = 'File.pdf'; link.href = 'https://storage.googleapis.com/bucketName/xyz.pdf'; link.click();
But same happen again file open in same tab instead of downloading. I don't know what is the main problem ? Is this Google bucket is not letting file to download, or my chrome setting preventing files to download. It is not downloading in Chrome i guess Chrome do allow the downloading from CORS files.
-
Amit Chauhan over 5 yearsSorry, but it does not work , But for workaround in pdfviewer we have a button to download pdf, but it is not downloading the pdf directly from clicking on button.
-
MT-FreeHK over 5 yearsHave you try it to download a pdf? It won't work for up-to-date browser.
-
Amit Chauhan over 5 yearsagree pdf also won't download
-
War over 5 yearssome browsers have built in functionality you cannot override ... it's a feature of the browser, after opening the browser will offer up a "save" option though as it has to download it in order to display in the first place.