user2309282
user2309282

Reputation: 121

Download file from server response with url as .json file

I have a web service that returns a file to requesting browser as url with .json extension. Ex:

https://somesite/rest/directories/output/_ags_SessionFile_f46fd461-b437-11e7-9dc1-005056bd201b.json

The intent is to simply navigate this url and invoke the "SaveAs" or simply save the .json file to the downloads directory.

This works in most instances, however on computers that do NOT have the .json file type association to IE (found in ControlPanel-->default programs) then the file is not downloaded or user prompted with SaveAs option and a new browser window is opened with the contents of the .json file displayed in the page.

I'm a bit unsure how to search for such a thing, even this post may be inadequate as I simply have not run into this issue ever.

   function downloadFile(results, messages) {
                    
                    //set a var of the complete url address that is returned from the GP service request
                    var urlOfFile = results[0].value.url;
                    
                    //get the div from the html of the widget
                    link = document.getElementById('downloadSession');

                    link.setAttribute('href', urlOfFile);
                    link.click();

                }

<div> 
    <a id="downloadSession" href="" target="_blank"></a>
</div>

Upvotes: 0

Views: 5212

Answers (2)

Andrew L
Andrew L

Reputation: 5496

Adding the HTML5 download attribute to the <a> tag should work for you

Anchor Tag doc

download HTML5

This attribute instructs browsers to download a URL instead of navigating to it, so the user will be prompted to save it as a local file

The docs also note some gotchas like it will only work for same-origin URLs and a few others so its worth a read.

Unfortunately the download attribute is not supported in Internet Explorer so for the download to work properly you will have to add Content-Type and Content-Disposition headers on the response from the server

they should look something like:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.json\"

Upvotes: 1

Sheetal Kumar Maurya
Sheetal Kumar Maurya

Reputation: 174

Add header:

header('Content-disposition: attachment; filename=file.json');
header('Content-type: application/json');
echo $json;

Upvotes: 0

Related Questions