Download file from server response with url as .json file - javascript

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>

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\"

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

Related

How to display a PDF without downloading

I have a PDF like like this:
"http://centraldata.s3.amazonaws.com/.....pdf?AWSAccessKeyId=...."
which I get from an api call. Then I pass it into an link so that users can click and download it.
<a href={pdfUrl} />
So, my question is, is there a way to let user view the PDF without downloading it? Except passing the Url into an tag, I don't know if there is any other way to use this link
When you place a page of HTML in the Public Domain (World Wide Web) you are offering a service with Dis-positions (Download to later view this page after decoding download).
If you include images, text, audio, video or even a PDF via link, then you are offering to disposition a copy of the page content (be dispossessed of all with its content) from the server to the browser.
A web site can indicate to the browser that the download need not be viewed in the browser, (many browsers do not have a PDF viewer, or the browser may be secured to a safer setting such as Download Media ONLY) the HTTP response could include the html attachment headers:
Content-Type: application/pdf
Content-Disposition: attachment; filename="file.pdf"
A web site can indicate to the browser that the download need not be viewed in the browser, but there is a possibility if the user settings allow for inline viewing, (many browsers do not have a PDF viewer or it may be secured to a safer setting such as Download ONLY) the HTTP response should include the html attachment headers:
Content-Type: application/pdf
Content-Disposition: inline; filename="file.pdf"
To avoid problems with the text parsing of the optional filename (blob: or anything will be saved to filename at the discretion of the client dispossesser) then the proffered optional filename should be "double quoted".
User security settings should ideally be set to no-popups, like blanks, open secondary windows or target tabs, since those are unfriendly, anti-social server actions.
W3 Recommendation says
< a href="download-file.pdf" download >right click here for your options including view now< /a>
If you as my client have an inline PDF viewer active, here is an iframe should you wish to use it. (Your servant)
The next two related questions are
How can I stop that content I duplicated, from being duplicated as a copy by the client?, well clearly you cannot, since you willingly gave it away and once decrypted and decoded by the receiver it belongs to them as editable dis possessed content.
How can I mask the source URL ?, generally you can not since to decode the whole file and maintain it (if required) the sending caller ID must be maintained as an open comms channel during viewing. (Much like satellite download or Netflix recordings on demand.)
just use this
MyPDF

JavaScript - Open file without extension in new tab [duplicate]

Is there a way to force PDF files to open in the browser when the option "Display PDF in browser" is unchecked?
I tried using the embed tag and an iframe, but it only works when that option is checked.
What can I do?
To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To have the file downloaded rather than viewed:
Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"
The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.
How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).
The correct type is application/pdf for PDF, not application/force-download. This looks like a hack for some legacy browsers. Always use the correct mimetype if you can.
If you have control over the server code:
Forced download/prompt: use header("Content-Disposition", "attachment; filename=myfilename.myextension");
Browser tries to open it: use header("Content-Disposition", "inline; filename=myfilename.myextension");
No control over the server code:
Use the HTML5 download attribute. It uses the custom filename specified on the view side.
NOTE: I prefer setting the filename on the server side as you may have more information and can use common code.
(I misread the question, the following answer is about forcefully downloading the file instead of opening it in the browser)
If you are using HTML5 (and I guess nowadays everyone uses that), there is an attribute called download.
For example,
<a href="somepathto.pdf" download="filename">
Here filename is optional, but if provided, it will take this name for the downloaded file.
EDIT
I know this is the opposite of what the question asked. I am keeping the opposite answer for those (like me) who came searching for the opposite question (Evidence: this answer has more upvotes then downvotes)
I had the same issue and most of the above answers should resolve your issue. Unfortunately, even if i was receiving the content-type & content-disposition headers in the response but still my pdf was being downloaded rather than viewed. After brainstorming and trying for many hours.
The Culprit was firefox, well in a way it was me. Nervous Laughter
By default, when you open a pdf file in firefox, it will provide you with a popup to either save the pdf file or to open it directly and there is also a check box which says do this action automatically from now on and guess who selected it.
Due to this mistake, my pdf was being downloaded rather than viewed, even if had all the required headers in response. This is a simple mistake but cost me a good amount of time.
To resolve this, just go to settings and search for applications and change pdf setting to whatever you need.
This is for ASP.NET MVC
In your cshtml page:
<section>
<h4><i class="fa fa-download"></i> #Model.Name</h4>
<object data="#Url.Action("View", "Document", new { id = #Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
<h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
</object>
</section>
In your controller:
public ActionResult Download(Guid id)
{
if (id == Guid.Empty)
return null;
var model = GetModel(id);
return File(model.FilePath, "application/pdf", model.FileName);
}
public FileStreamResult View(Guid id)
{
if (id == Guid.Empty)
return null;
var model = GetModel(id);
FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
While the following works well on firefox, it DOES NOT work on chrome and mobile browsers.
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To fix the chrome & mobile browsers error, do the following:
Store your files on a directory in your project
Use the google PDF Viewer
Google PDF Viewer can be used as so:
<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></iframe>
If you have Apache add this to the .htaccess file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
Oops, there were typing errors in my previous post.
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
If you don't want the browser to prompt the user then use "inline" for the third string instead of "attachment". Inline works very well. The PDF display immediately without asking the user to click on Open. I've used "attachment" and this will prompt the user for Open, Save. I've tried to change the browser setting nut it doesn't prevent the prompt.
for large files you need to get your output buffer started add :-
ob_start(); // at the start
..//your code
ob_clean();// at the end of you file
You can do this in the following way:
Open PDF
If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:
<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
Order Allow,Deny
Allow from all
</FilesMatch>
But now allow just certain necessary files.
I have used this code and it worked perfectly.
Open downloads.php from rootfile.
Then go to line 186 and change it to the following:
if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
$mime = getimagesize($download_location);
if(!empty($mime)) {
header("Content-Type: {$mime['mime']}");
}
}
elseif(preg_match("/\.pdf/i", $name)){
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
}
else{
header("Content-Type: application/force-download");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$name."\";");
}
Here is another method of forcing a file to view in the browser in PHP:
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
echo '<html>'
.header('Content-Type: application/'.$extension).'<br>'
.header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
.'<body>'
.'<object style="overflow: hidden; height: 100%;
width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
<embed src="'.$url.'" type="application/'.$extension.'" />
</object>'
.'</body>'
. '</html>';
Either use
<embed src="file.pdf" />
if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff
If you link to a .PDF it will open in the browser.
If the box is unchecked it should link to a .zip to force the download.
If a .zip is not an option, then use headers in PHP to force the download
header('Content-Type: application/force-download');
header('Content-Description: File Transfer');

How to set name to Streamable download links with tokens at it's end?

I'm trying to set name to the streamable download links with some token id's at its end. I used the HTML5 Download attribute and Content-Disposition Methods but it won't work for me. I'm using PHP codes to extract the streaming links
I used this method:
<a href="https://cf-media.sndcdn.com/dxsZzMQL3TdG.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNl..........warBhKbR7Lr86aDLOdkjkDSNprxVyN3ClwEgUmGMwSC6jCwN~p4Ww__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ" download="Despacito.mp3" > Download </a>
It doesn't work.
Any way to download the file with required name ??
I'm not fully sure what you mean by streamable, but I assume you want that the user would download a mp3 file that has a unique name on your server and once downloaded it would be given by default another name that the name of the file on your server.
This can be done by editing the headers of your file
on the html side it would look like
Download
and in your download.php file it would look like
<?php
if($_GET['file'] == 'dxsZzMQL3TdG.128.mp3') {
header('Content-Type: audio/mpeg3');
header('Content-Disposition: attachment; filename="Despacito.mp3"');
readfile('dxsZzMQL3TdG.128.mp3');
}

Check URL contains query string to download then open in new tab [duplicate]

Is there a way to force PDF files to open in the browser when the option "Display PDF in browser" is unchecked?
I tried using the embed tag and an iframe, but it only works when that option is checked.
What can I do?
To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To have the file downloaded rather than viewed:
Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"
The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.
How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).
The correct type is application/pdf for PDF, not application/force-download. This looks like a hack for some legacy browsers. Always use the correct mimetype if you can.
If you have control over the server code:
Forced download/prompt: use header("Content-Disposition", "attachment; filename=myfilename.myextension");
Browser tries to open it: use header("Content-Disposition", "inline; filename=myfilename.myextension");
No control over the server code:
Use the HTML5 download attribute. It uses the custom filename specified on the view side.
NOTE: I prefer setting the filename on the server side as you may have more information and can use common code.
(I misread the question, the following answer is about forcefully downloading the file instead of opening it in the browser)
If you are using HTML5 (and I guess nowadays everyone uses that), there is an attribute called download.
For example,
<a href="somepathto.pdf" download="filename">
Here filename is optional, but if provided, it will take this name for the downloaded file.
EDIT
I know this is the opposite of what the question asked. I am keeping the opposite answer for those (like me) who came searching for the opposite question (Evidence: this answer has more upvotes then downvotes)
I had the same issue and most of the above answers should resolve your issue. Unfortunately, even if i was receiving the content-type & content-disposition headers in the response but still my pdf was being downloaded rather than viewed. After brainstorming and trying for many hours.
The Culprit was firefox, well in a way it was me. Nervous Laughter
By default, when you open a pdf file in firefox, it will provide you with a popup to either save the pdf file or to open it directly and there is also a check box which says do this action automatically from now on and guess who selected it.
Due to this mistake, my pdf was being downloaded rather than viewed, even if had all the required headers in response. This is a simple mistake but cost me a good amount of time.
To resolve this, just go to settings and search for applications and change pdf setting to whatever you need.
This is for ASP.NET MVC
In your cshtml page:
<section>
<h4><i class="fa fa-download"></i> #Model.Name</h4>
<object data="#Url.Action("View", "Document", new { id = #Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
<h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
</object>
</section>
In your controller:
public ActionResult Download(Guid id)
{
if (id == Guid.Empty)
return null;
var model = GetModel(id);
return File(model.FilePath, "application/pdf", model.FileName);
}
public FileStreamResult View(Guid id)
{
if (id == Guid.Empty)
return null;
var model = GetModel(id);
FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
While the following works well on firefox, it DOES NOT work on chrome and mobile browsers.
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To fix the chrome & mobile browsers error, do the following:
Store your files on a directory in your project
Use the google PDF Viewer
Google PDF Viewer can be used as so:
<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></iframe>
If you have Apache add this to the .htaccess file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
Oops, there were typing errors in my previous post.
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
If you don't want the browser to prompt the user then use "inline" for the third string instead of "attachment". Inline works very well. The PDF display immediately without asking the user to click on Open. I've used "attachment" and this will prompt the user for Open, Save. I've tried to change the browser setting nut it doesn't prevent the prompt.
for large files you need to get your output buffer started add :-
ob_start(); // at the start
..//your code
ob_clean();// at the end of you file
You can do this in the following way:
Open PDF
If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:
<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
Order Allow,Deny
Allow from all
</FilesMatch>
But now allow just certain necessary files.
I have used this code and it worked perfectly.
Open downloads.php from rootfile.
Then go to line 186 and change it to the following:
if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
$mime = getimagesize($download_location);
if(!empty($mime)) {
header("Content-Type: {$mime['mime']}");
}
}
elseif(preg_match("/\.pdf/i", $name)){
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
}
else{
header("Content-Type: application/force-download");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$name."\";");
}
Here is another method of forcing a file to view in the browser in PHP:
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
echo '<html>'
.header('Content-Type: application/'.$extension).'<br>'
.header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
.'<body>'
.'<object style="overflow: hidden; height: 100%;
width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
<embed src="'.$url.'" type="application/'.$extension.'" />
</object>'
.'</body>'
. '</html>';
Either use
<embed src="file.pdf" />
if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff
If you link to a .PDF it will open in the browser.
If the box is unchecked it should link to a .zip to force the download.
If a .zip is not an option, then use headers in PHP to force the download
header('Content-Type: application/force-download');
header('Content-Description: File Transfer');

Download image direct from url

Let's say that I have some URL to an image on the web. Let's say the URL is http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg
Now, when a user press the download button, the image should be downloaded.
I've tried this:
window.location.href = Link;
But sometimes it just opens the image on the browser and sometimes it is downloaded as I wanted.
How can I achieve this?
You can use the HTML5 download attribute on anchors :
<a href="http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg" download="http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg">
<img src="http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg">
</a>
You need to pass appropriate headers in order to allow user to download the file. If you just provide the file link in the url the browsers interpret it differently. They may first try to open the file in the browser, if it fails the file will be prompt as force-download.
If you are using PHP, the headers in download script is something like:
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; file="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Cache-control: private");
header('Pragma: private');
The full tutorial can be found here: www.phptutorialforbeginners.com/2013/04/file-download-script-in-php-php.html
You will have to set Content-Disposition header field, as suggested by http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html, if you want the image should not be handled natively by browser. If you use PHP, may be this link would help, http://w3schools.invisionzone.com/index.php?showtopic=39943
Only issue with this, you can't directly make apache serve you this file, as a normal static resource, or I don't know the way to do this Apache :)

Categories

Resources