Related
I have some big size PDF catalogs at my website, and I need to link these as download. When I googled, I found such a thing noted below. It should open the "Save As..." popup at link click...
<head>
<meta name="content-disposition" content="inline; filename=filename.pdf">
...
But it doesn't work :/ When I link to a file as below, it just links to file and is trying to open the file.
File name
UPDATE (according to answers below):
As I see there is no 100% reliable cross-browser solution for this. Probably the best way is using one of the web services listed below, and giving a download link...
http://box.net/
http://droplr.com/
http://getcloudapp.com/
From an answer to Force a browser to save file as after clicking link:
<a href="path/to/file" download>Click here to download</a>
Use the download attribute, but take into account that it only works for files hosted in the same origin that your code. It means that users can only download files that are from the origin site, same host.
Download with original filename:
Click here to download
Download with 'some_name' as filename:
Click here to download
Adding target="_blank" we will use a new Tab instead of the actual one, and also it will contribute to the proper behavior of the download attribute in some scenarios.
It follows the same rules as same-origin policy. You can learn more about this policy on the MDN Web Doc same-origin policy page
You can lern more about this download HTML5 attribute on the MDN Web Doc anchor's attributes page.
Meta tags are not a reliable way to achieve this result. Generally you shouldn't even do this - it should be left up to the user/user agent to decide what do to with the content you provide. The user can always force their browser to download the file if they wish to.
If you still want to force the browser to download the file, modify the HTTP headers directly. Here's a PHP code example:
$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary'); // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes'); // Allow support for download resume
header('Content-Length: ' . filesize($path)); // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf'); // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename); // Make the browser display the Save As dialog
readfile($path); // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb
Note that this is just an extension to the HTTP protocol; some browsers might ignore it anyway.
I had this same issue and found a solution that has worked great so far. You put the following code in your .htaccess file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
It came from Force a File to Download Instead of Showing Up in the Browser.
I found a very simple solution for Firefox (only works with a relative rather than a direct href): add type="application/octet-stream":
Example
Generally it happens, because some browsers settings or plug-ins directly open PDF in the same window like a simple web page.
The following might help you. I have done it in PHP a few years back. But currently I'm not working on that platform.
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
}
else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
Save the above as download.php.
Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.
You can use it like so:
Add the following link to your HTML file.
Download the cool PDF.
Reference from: This blog
Try adding this line to your .htaccess file.
AddType application/octet-stream .pdf
I hope it'll work as it is browser independent.
I just used this, but I don't know if it works across all browsers.
It works in Firefox:
<a href="myfile.pdf" download>Click to Download</a>
A really simple way to achieve this, without using external download sites or modifying headers etc. is to simply create a ZIP file with the PDF inside and link directly to the ZIP file. This will ALWAYS trigger the Save/Open dialog, and it's still easy for people to double-click the PDF windows the program associated with .zip is launched.
BTW great question, I was looking for an answer as well, since most browser-embedded PDF plugins take sooo long to display anything (and will often hang the browser whilst the PDF is loading).
Just put the below code in your .htaccess file:
AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf
Or you can also do trick by JavaScript
element.setAttribute( 'download', whatever_string_you_want);
A very easy way to do this, if you need to force download for a single link on your page, is to use the HTML5 download-attribute in the href-link.
See: http://davidwalsh.name/download-attribute
with this you can rename the file that the user will download and at the same time it forces the download.
There has been a debate whether this is good practice or not, but in my case I have an embedded viewer for a PDF file and the viewer does not offer a download link, so i have to provide one separately. Here I want to make sure the user does not get the PDF opened in the web browser, which would be confusing.
This won't necessary open the save as-dialog, but will download the link straight to the preset download destination. And of course if you are doing a site for someone else, and need them to write in manually attributes to their links is probably a bad idea, but if there is way to get the attribute into the links, this can be a light solution.
A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.
One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:
http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf
Here is the code:
class HTTPFilestoreHandler(SimpleHTTPRequestHandler):
def __init__(self, fs_path, *args):
self.fs_path = fs_path # Filestore path
SimpleHTTPRequestHandler.__init__(self, *args)
def send_head(self):
# Overwrite SimpleHTTPRequestHandler.send_head to force download name
path = self.path
get_index = (path == '/')
self.log_message("path: %s" % path)
if '/download_as/' in path:
p_parts = path.split('/download_as/')
assert len(p_parts) == 2, 'Bad download link:' + path
path, download_as = p_parts
path = self.translate_path(path )
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# Redirect browser - doing basically what Apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Expires", '0')
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
self.send_header("Content-Transfer-Encoding", 'binary')
if download_as:
self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
self.send_header("Content-Length", str(fs[6]))
self.send_header("Connection", 'close')
self.end_headers()
return f
class HTTPFilestoreServer:
def __init__(self, fs_path, server_address):
def handler(*args):
newHandler = HTTPFilestoreHandler(fs_path, *args)
newHandler.protocol_version = "HTTP/1.0"
self.server = BaseHTTPServer.HTTPServer(server_address, handler)
def serve_forever(self, *args):
self.server.serve_forever(*args)
def start_server(fs_path, ip_address, port):
server_address = (ip_address, port)
httpd = HTTPFilestoreServer(fs_path, server_address)
sa = httpd.server.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
This is old post but here is the one my solution in JavaScript what using jQuery library.
<script>
(function($){
var download = [];
$('a.force-download, .force-download a').each(function(){
// Collect info
var $this = $(this),
$href = $this.attr('href'),
$split = $href.split('/'),
$name = document.title.replace(/[\W_]/gi, '-').replace(/-{2,}/g, '-'); // get title and clean it for the URL
// Get filename from URL
if($split[($split.length-1)])
{
$tmp = $split[($split.length-1)];
$tmp = $tmp.split('.');
$name = $tmp[0].replace(/[\W_]/gi, '-').replace(/-{2,}/g, '-');
}
// If name already exists, put timestamp there
if($.inArray($name, download) > -1)
{
$name = $name + '-' + Date.now().replace(/[\W]/gi, '-');
}
$(this).attr("download", $name);
download.push($name);
});
}(jQuery || window.jQuery))
</script>
You just need to use class force-download inside your <a> tag and will force download automaticaly. You also can add it to parent div and will pickup all links inside it.
Example:
Download PDF
This is great for WordPress and any other systems or custom websites.
Add a response header Content-Disposition:attachment; followed by the file name. Remove the Meta Content-Disposition;Inline; which will open the document in the same window
In java it is set as
response.setHeader("Content-Disposition", "attachment;filename=test.jpg");
After the file name in the HTML code I add ?forcedownload=1
This has been the simplest way for me to trigger a dialog box to save or download.
If you have a plugin within the browser which knows how to open a PDF file it will open directly. Like in case of images and HTML content.
So the alternative approach is not to send your MIME type in the response. In this way the browser will never know which plugin should open it. Hence it will give you a Save/Open dialog box.
I just had a very similar issue with the added problem that I needed to create download links to files inside a ZIP file.
I first tried to create a temporary file, then provided a link to the temporary file, but I found that some browsers would just display the contents (a CSV Excel file) rather than offering to download. Eventually I found the solution by using a servlet. It works both on Tomcat and GlassFish, and I tried it on Internet Explorer 10 and Chrome.
The servlet takes as input a full path name to the ZIP file, and the name of the file inside the zip that should be downloaded.
Inside my JSP file I have a table displaying all the files inside the zip, with links that say: onclick='download?zip=<%=zip%>&csv=<%=csv%>'
The servlet code is in download.java:
package myServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;
import java.util.*;
// Extend HttpServlet class
public class download extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter(); // now we can write to the client
String filename = request.getParameter("csv");
String zipfile = request.getParameter("zip");
String aLine = "";
response.setContentType("application/x-download");
response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
ZipFile zip = new ZipFile(zipfile);
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.toString().equals(filename)) {
InputStream is = zip.getInputStream(entry);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
while ((aLine = br.readLine()) != null) {
out.println(aLine);
}
is.close();
break;
}
}
}
}
To compile on Tomcat you need the classpath to include tomcat\lib\servlet-api.jar or on GlassFish: glassfish\lib\j2ee.jar
But either one will work on both. You also need to set your servlet in web.xml.
Chrome 91 had a new change, it supported in chrome 86-90 and 91+.
The following syntax will make it happen.
const fileHandle = await self.showSaveFilePicker({
suggestedName: 'Untitled Text.txt',
types: [{
description: 'Text documents',
accept: {
'text/plain': ['.txt'],
},
}],
});
Read more here:
https://developer.chrome.com/blog/new-in-chrome-91/
**Another solution you can just make it as a blob and then use saveAs **
const blob = fetch("some-url-here").then(data => data.blob());
saveAs(blob, "filename.txt")
With large PDF files the browser hangs.
In Mozilla, menu Tools → Options → Applications, then next to the content type Adobe Acrobat document.
In the Action drop down, select Always ask.
This did not work for me, so what worked was:
Menu Tools* → Add-ons → Adobe Acrobat (Adobe PDF plugin for Firefox) → DISABLE.
Now I am able to download e-books!
I have some big size PDF catalogs at my website, and I need to link these as download. When I googled, I found such a thing noted below. It should open the "Save As..." popup at link click...
<head>
<meta name="content-disposition" content="inline; filename=filename.pdf">
...
But it doesn't work :/ When I link to a file as below, it just links to file and is trying to open the file.
File name
UPDATE (according to answers below):
As I see there is no 100% reliable cross-browser solution for this. Probably the best way is using one of the web services listed below, and giving a download link...
http://box.net/
http://droplr.com/
http://getcloudapp.com/
From an answer to Force a browser to save file as after clicking link:
<a href="path/to/file" download>Click here to download</a>
Use the download attribute, but take into account that it only works for files hosted in the same origin that your code. It means that users can only download files that are from the origin site, same host.
Download with original filename:
Click here to download
Download with 'some_name' as filename:
Click here to download
Adding target="_blank" we will use a new Tab instead of the actual one, and also it will contribute to the proper behavior of the download attribute in some scenarios.
It follows the same rules as same-origin policy. You can learn more about this policy on the MDN Web Doc same-origin policy page
You can lern more about this download HTML5 attribute on the MDN Web Doc anchor's attributes page.
Meta tags are not a reliable way to achieve this result. Generally you shouldn't even do this - it should be left up to the user/user agent to decide what do to with the content you provide. The user can always force their browser to download the file if they wish to.
If you still want to force the browser to download the file, modify the HTTP headers directly. Here's a PHP code example:
$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary'); // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes'); // Allow support for download resume
header('Content-Length: ' . filesize($path)); // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf'); // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename); // Make the browser display the Save As dialog
readfile($path); // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb
Note that this is just an extension to the HTTP protocol; some browsers might ignore it anyway.
I had this same issue and found a solution that has worked great so far. You put the following code in your .htaccess file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
It came from Force a File to Download Instead of Showing Up in the Browser.
I found a very simple solution for Firefox (only works with a relative rather than a direct href): add type="application/octet-stream":
Example
Generally it happens, because some browsers settings or plug-ins directly open PDF in the same window like a simple web page.
The following might help you. I have done it in PHP a few years back. But currently I'm not working on that platform.
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
}
else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
Save the above as download.php.
Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.
You can use it like so:
Add the following link to your HTML file.
Download the cool PDF.
Reference from: This blog
Try adding this line to your .htaccess file.
AddType application/octet-stream .pdf
I hope it'll work as it is browser independent.
I just used this, but I don't know if it works across all browsers.
It works in Firefox:
<a href="myfile.pdf" download>Click to Download</a>
A really simple way to achieve this, without using external download sites or modifying headers etc. is to simply create a ZIP file with the PDF inside and link directly to the ZIP file. This will ALWAYS trigger the Save/Open dialog, and it's still easy for people to double-click the PDF windows the program associated with .zip is launched.
BTW great question, I was looking for an answer as well, since most browser-embedded PDF plugins take sooo long to display anything (and will often hang the browser whilst the PDF is loading).
Just put the below code in your .htaccess file:
AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf
Or you can also do trick by JavaScript
element.setAttribute( 'download', whatever_string_you_want);
A very easy way to do this, if you need to force download for a single link on your page, is to use the HTML5 download-attribute in the href-link.
See: http://davidwalsh.name/download-attribute
with this you can rename the file that the user will download and at the same time it forces the download.
There has been a debate whether this is good practice or not, but in my case I have an embedded viewer for a PDF file and the viewer does not offer a download link, so i have to provide one separately. Here I want to make sure the user does not get the PDF opened in the web browser, which would be confusing.
This won't necessary open the save as-dialog, but will download the link straight to the preset download destination. And of course if you are doing a site for someone else, and need them to write in manually attributes to their links is probably a bad idea, but if there is way to get the attribute into the links, this can be a light solution.
A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.
One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:
http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf
Here is the code:
class HTTPFilestoreHandler(SimpleHTTPRequestHandler):
def __init__(self, fs_path, *args):
self.fs_path = fs_path # Filestore path
SimpleHTTPRequestHandler.__init__(self, *args)
def send_head(self):
# Overwrite SimpleHTTPRequestHandler.send_head to force download name
path = self.path
get_index = (path == '/')
self.log_message("path: %s" % path)
if '/download_as/' in path:
p_parts = path.split('/download_as/')
assert len(p_parts) == 2, 'Bad download link:' + path
path, download_as = p_parts
path = self.translate_path(path )
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# Redirect browser - doing basically what Apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Expires", '0')
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
self.send_header("Content-Transfer-Encoding", 'binary')
if download_as:
self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
self.send_header("Content-Length", str(fs[6]))
self.send_header("Connection", 'close')
self.end_headers()
return f
class HTTPFilestoreServer:
def __init__(self, fs_path, server_address):
def handler(*args):
newHandler = HTTPFilestoreHandler(fs_path, *args)
newHandler.protocol_version = "HTTP/1.0"
self.server = BaseHTTPServer.HTTPServer(server_address, handler)
def serve_forever(self, *args):
self.server.serve_forever(*args)
def start_server(fs_path, ip_address, port):
server_address = (ip_address, port)
httpd = HTTPFilestoreServer(fs_path, server_address)
sa = httpd.server.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
This is old post but here is the one my solution in JavaScript what using jQuery library.
<script>
(function($){
var download = [];
$('a.force-download, .force-download a').each(function(){
// Collect info
var $this = $(this),
$href = $this.attr('href'),
$split = $href.split('/'),
$name = document.title.replace(/[\W_]/gi, '-').replace(/-{2,}/g, '-'); // get title and clean it for the URL
// Get filename from URL
if($split[($split.length-1)])
{
$tmp = $split[($split.length-1)];
$tmp = $tmp.split('.');
$name = $tmp[0].replace(/[\W_]/gi, '-').replace(/-{2,}/g, '-');
}
// If name already exists, put timestamp there
if($.inArray($name, download) > -1)
{
$name = $name + '-' + Date.now().replace(/[\W]/gi, '-');
}
$(this).attr("download", $name);
download.push($name);
});
}(jQuery || window.jQuery))
</script>
You just need to use class force-download inside your <a> tag and will force download automaticaly. You also can add it to parent div and will pickup all links inside it.
Example:
Download PDF
This is great for WordPress and any other systems or custom websites.
Add a response header Content-Disposition:attachment; followed by the file name. Remove the Meta Content-Disposition;Inline; which will open the document in the same window
In java it is set as
response.setHeader("Content-Disposition", "attachment;filename=test.jpg");
After the file name in the HTML code I add ?forcedownload=1
This has been the simplest way for me to trigger a dialog box to save or download.
If you have a plugin within the browser which knows how to open a PDF file it will open directly. Like in case of images and HTML content.
So the alternative approach is not to send your MIME type in the response. In this way the browser will never know which plugin should open it. Hence it will give you a Save/Open dialog box.
I just had a very similar issue with the added problem that I needed to create download links to files inside a ZIP file.
I first tried to create a temporary file, then provided a link to the temporary file, but I found that some browsers would just display the contents (a CSV Excel file) rather than offering to download. Eventually I found the solution by using a servlet. It works both on Tomcat and GlassFish, and I tried it on Internet Explorer 10 and Chrome.
The servlet takes as input a full path name to the ZIP file, and the name of the file inside the zip that should be downloaded.
Inside my JSP file I have a table displaying all the files inside the zip, with links that say: onclick='download?zip=<%=zip%>&csv=<%=csv%>'
The servlet code is in download.java:
package myServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;
import java.util.*;
// Extend HttpServlet class
public class download extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter(); // now we can write to the client
String filename = request.getParameter("csv");
String zipfile = request.getParameter("zip");
String aLine = "";
response.setContentType("application/x-download");
response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
ZipFile zip = new ZipFile(zipfile);
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.toString().equals(filename)) {
InputStream is = zip.getInputStream(entry);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
while ((aLine = br.readLine()) != null) {
out.println(aLine);
}
is.close();
break;
}
}
}
}
To compile on Tomcat you need the classpath to include tomcat\lib\servlet-api.jar or on GlassFish: glassfish\lib\j2ee.jar
But either one will work on both. You also need to set your servlet in web.xml.
Chrome 91 had a new change, it supported in chrome 86-90 and 91+.
The following syntax will make it happen.
const fileHandle = await self.showSaveFilePicker({
suggestedName: 'Untitled Text.txt',
types: [{
description: 'Text documents',
accept: {
'text/plain': ['.txt'],
},
}],
});
Read more here:
https://developer.chrome.com/blog/new-in-chrome-91/
**Another solution you can just make it as a blob and then use saveAs **
const blob = fetch("some-url-here").then(data => data.blob());
saveAs(blob, "filename.txt")
With large PDF files the browser hangs.
In Mozilla, menu Tools → Options → Applications, then next to the content type Adobe Acrobat document.
In the Action drop down, select Always ask.
This did not work for me, so what worked was:
Menu Tools* → Add-ons → Adobe Acrobat (Adobe PDF plugin for Firefox) → DISABLE.
Now I am able to download e-books!
I have a piece of code that downloads excel reports which works absolutely perfectly on my local web server but when deployed the excel file is always corrupted, code samples below:
AngularJS:
$scope.getExcelFile = function(dateFrom, dateTo){
API.getExcelFile(dateFrom, dateTo).then(function(data){
var blob = {
data: [data.data],
filename: 'ExcelFile.xlsx',
options: {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}
FileSaver.saveAs(blob);
});
}
API(JS):
this.getExcelFile= function(dateFrom, dateTo){
var promise = $http({
url: '/some/api/endpoint/' + dateFrom + '/' + dateTo,
method:'GET',
responseType: 'arraybuffer'
})
return promise;
PHP API - Note I can't provide all the code for the way this is created but I think it's safe to say it's to do with server/response issues rather than file construction since it works fine locally..
$excelFileName = "ExcelFile.xlsx";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $excelFileName . '"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output'); // Output to browser
One thing I have noticed is different is that the remote response has a blank line before all the excel binary stuff when I look at it in the chrome inspector, locally it doesn't have this.
Any suggestions around how to resolve this would be greatly appreciated
Ok rather embarrassingly this was the result of a stray newline after the closing ?> on a configuration script at the top of the API. Hence the blank newline in the response.
Ideally you shouldn't use ?> at the bottom of PHP scripts at all any more, this was a legacy script.
(face palm)
I have a Javascript program that extracts data from a text file (just a plain *.txt file) and then displays it in a table. It works as intended except for one issue: If I update the text file where the data lives in the update does not shows up on the table. The reason is that the file is being cached by the browser.
Is there a way to force Javascript to read from the latest version of the file and not from the cached version? Again, this is not a problem with the javascript file as doing Ctrl-5 and or Shift+Ctrl+R does not works and also updating the javascript file itself behaves as expected. it is only the file where the data is in that is the problem.
To read the text file I use the Webix toolkit which uses AJAX to read the file. The reading and parsing of the text file is done via Javascript and the Webix toolkit. There is very little html in my program.
//the name of the file is dependant of an user specified input
var theURL = rossObj.store_number.store_number + "macaddress.txt ";
webix.ajax(theURL,{
//response
error:function(text, xml, XmlHttpRequest){
webix.alert({ ok:"OK", type:"alert-warning", text:"could not open the following URL --> "+theURL, width:"400px"});
return "mac_address_error";
},
success:function(text, xml, XmlHttpRequest){
//parse the file;
}
});
Try adding a random number to the end of the url as a query string, the server will ignore but the browser will treat it as a new file
var theURL = rossObj.store_number.store_number +
"macaddress.txt?" +
Math.floor((Math.random() * 10000) + 1);
I've a DataSnap server method
function TServerMethods.GetFile(filename): TStream
returning a file.
In my test case the file is a simple .PDF.
I'm sure this function works fine, as I'm able to open files on ObjectiveC client side app's where I've used my own http call to the DataSnap method (no Delphi proxy).
The stream is read from ASIHttpRequest object and saved as local file, then loaded and regulary shown in standard pdf reader.
I do not kown how exactly ASIHttpRequest manages the returned data.
But on JavaScript client side where I use standard
stream = ServerMethods().GetFile('test.pdf')
JavaScript function, as provided from DataSnap proxy itself, I do not figure out how to show the .pdf data to the user.
Using
window.open().document.write(stream);
a new browser window opens with textual raw data ( %PDF-1.5 %âãÏÓ 1 0 obj << /Type /Catalog /Pages 2 0 R …..)
With
window.open("data:application/pdf;base64," +stream);
I get an empty new browser page.
With
window.open("data:application/pdf," +stream);
or
document.location = 'data:application/pdf,'+encodeURIComponent(serverMethods().GetFile('test'));
I get an new browser page with pdf empry reader and alert “This PDF document could not be displayed correctly”
Nothing changes adding:
GetInvocationMetadata().ResponseContentType := 'application/pdf';
into the DataSnap function.
I've no other ideas...
EDIT
The task is for a general file download, not only PDF. PDF is a test only. GetFile have to manage .pdf, .xlsx, .docx, .png, .eml, etc...
Your server side code works as expected once you set the ResponseContentType. You can test this by calling the method directly from a browser. Change the class name to match the one you're using:
http://localhost:8080/datasnap/rest/TServerMethods1/GetFile/test.pdf
I'm sure there's a way to display the stream properly on the browser side, but I'm not sure what that is. Unless you're doing something special with the stream, I'd recommend getting the document directly or using a web action and getting out of the browser's way. Basically what mjn suggested.
I can think of a couple of solutions.
1) A quick way would be to allow access to the documents directly.
In the WebFileDispatcher, add a WebFileExtension. Select .pdf and it will fill in the mime type for you. Assuming your pdf documents are in the "docs" folder, the url might look like this:
http://localhost:8080/docs/test.pdf
2) I would probably add an action on the web module. It's a little more involved, but it also gives me more control.
Using this url:
http://localhost:8080/getfile?filename=test.pdf
And code like this in the web action handler (no checking or error handling). The Content-Disposition header suggests a file name for the downloaded file:
procedure TWebModule1.WebModule1GetFileActionAction(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
lStream: TMemoryStream;
lFilename: string;
begin
lFilename := Request.QueryFields.Values['filename'];
lStream := TMemoryStream.Create;
lStream.LoadFromFile('.\Docs\' + lFilename);
lStream.Position := 0;
Response.ContentStream := lStream;
Response.ContentType := 'application/pdf';
Response.SetCustomHeader('Content-Disposition',
Format('attachment; filename="%s"', [lFilename]));
end;