简体   繁体   English

从服务器响应下载文件,URL为.json文件

[英]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. 我有一个Web服务,该文件以url为扩展名的.json返回文件到请求浏览器。 Ex: 例如:

https://somesite/rest/directories/output/_ags_SessionFile_f46fd461-b437-11e7-9dc1-005056bd201b.json 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. 目的是简单地浏览此URL并调用“ SaveAs”,或简单地将.json文件保存到downloads目录。

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. 这在大多数情况下都有效,但是在不具有与IE关联的.json文件类型(在ControlPanel->默认程序中找到)的计算机上,则不会下载该文件或用户使用SaveAs选项提示并打开一个新的浏览器窗口并在页面中显示.json文件的内容。

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>

Adding the HTML5 download attribute to the <a> tag should work for you 将HTML5 download属性添加到<a>标记中应该对您<a>

Anchor Tag doc 锚标签文档

download HTML5 下载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 此属性指示浏览器下载URL而不是导航到URL,因此将提示用户将其保存为本地文件。

The docs also note some gotchas like it will only work for same-origin URLs and a few others so its worth a read. 该文档还指出了一些陷阱,例如它仅适用于同源URL和其他一些URL,因此值得一读。

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 不幸的是,Internet Explorer不支持download属性,因此要使下载正常工作,您将必须在服务器的响应上添加Content-TypeContent-Disposition标头

they should look something like: 他们应该看起来像:

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

Add header: 添加标题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM