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

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');

Related

Force IE11 to save download CSV file

I am trying to download a CSV file to the browser.
I am unable to get it to properly download the file in IE11. Instead it opens a new tab and write the CSV contents to the tab.
I am using just the following javascript:
window.open(sUrl, '_target');
In the IE Developer tools, I can see the Response Header shows:
Content-Type: text/csv; charset=UTF-8
I would like it to prompt the user to save the file.
I've changed the browser settings to always download, yet it still doesn't do it.
I would like to fix this from a change to the Javascript, if possible.
How can I do that?
As far as I know, it's not possible to do this with JavaScript. Take a look at this answer if you're comforable using PHP to download the file.
According to that answer, your PHP should look something like this:
<?php
$file_url = 'http://www.myremoteserver.com/file.csv';
header('Content-Type: text/csv; charset=UTF-8');
header("Content-Transfer-Encoding: Quoted-Printable");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>

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>
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;

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 :)

save as dialog box in Firefox

I want to show the Save as dialog box when a user clicks an HTML button.
I am using DOJO and JavaScript.
In IE document.exec comes to rescue but in Firefox one needs to make changes in filesystem to use NSI.
Any idea will be appreciated.
You can force the browser to download some data using a data url:
content = "This is the text for downloading";
window.location.href = "data:application/octet-stream,"+
encodeURIComponent(content);
The main problem with this is that the user will not be able to choose a filename and the generated filename is some random hash. If you don't mind using Flash, you could use Downloadify, this will give you more control over the Save dialog.
Have the HTML button href to a unknown document type. Say FileName.xxxblah.
This will automatically trigger the Save as Dialog.
It's not exactly what you're looking for, but the only reliable way I know of is to create a server side script on the server which will send the correct headers. In PHP this is how you'd do it:
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="mydocument.csv";' );
header('Content-length: '.(int)strlen($csvData));
print($csvData);
Content-type is the "mime type" of the document, and for compatibility with some browsers it's important this perfectly matches the extension of the filename.
Content-Disposition: attachment instructs the browser to download the page, even if it wouldn't normally do so for that mime-type, and you're able to provide the filename.
Content-length is the size of the download, this is optional but it must be provided if you want the user to see a progress bar for the download.
Some browsers will present a save as dialog, while others will simply save the file to the user's preferred download folder. You don't have much control over which will happen.

Categories

Resources