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 :)
Related
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');
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);
?>
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');
}
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');
i have been working on a website which will allow users to upload and download files. The file is renamed on upload and stored on my server. But when it is downloaded, it has to be renamed i.e to its original name. Presently i am using the following to do so :
Download
But the "download" attribute does not work with firefox. Any alternative using javascript or jquery ? I am using php for server side.
Edit:
Thanks for the solution using php. But that is not what i am looking for. I am using a custom file viewer using javascript. On clicking the thumbnail of the file, the viewer is displayed. An AJAX request is sent to get the link to the file. The response (the link) is used to display the file, also is added to the tag for download. A php solution would mean a page reload on every request, which i want to avoid. So any javascript or jquery solutions ?
On the server use header("Content-Disposition: attachment; filename='Original name'")
Try Below Code
header('Content-Disposition: attachment; filename='.basename('newfilename.txt'));
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('filename.txt'));
ob_clean();
flush();
readfile('filename.txt');