How to force a pdf download automatically? - pdf

Is there any way to force the user's download-manager to start a download for .PDF instead of showing the .PDF in a new window/tab?

use the download attribute inside your <a> tag
<a href="content/file.pdf" download > pdf link </a>
<a href="content/file.doc" download > doc link </a>

Set Content-Disposition in your HttpResponse header:
Content-Disposition = 'attachment; filename=filename.pdf'

This needs to be done in the server side. You can't do this at the client side.
How to do it depends on the server side language in question.
PHP:
header('Content-Disposition: attachment; filename="' . $filename . '"');
Java:
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
.NET:
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
If there's no means of any server side code which streams the PDF file, then you need to configure it at webserver level. In for example Apache HTTPD, you can place/expand a .htaccess file in the PDF folder's root with the following entry:
<Files *.pdf>
Header set Content-Disposition attachment
</Files>
or configure it globally in httpd.conf file. Similar approach exist for IIS with web.config file.

For IIS:
Put all files you want to force to download in their own folder.
Then in IIS go that folder and double click HTTP Response Headers.
Add a new header with the following info:
Name:
content-disposition
Value:
attachment
All files in that folder, when accessed, should prompt the save as dialog box for the appropriate browser.

You need to send HTTP headers ( Content-disposition ) in order to do this. You cannot do this on the client side.

.htaccess solution:
AddType application/octet-stream .pdf

<?php
header('Content-disposition: attachment; filename=filename.pdf');
header('Content-type: application/pdf');
readfile('path/to/filename.pdf');

Yes it can be done in JSP page... By giving a Download link in One JSP page on which goes to new script page...and download the PDF file as follows
DownloadPage.JSP code :-
<a href='downloadPdf.jsp?file=FILE.pdf' >Download PDF File</a>
downloadPdf.JSP code :-
<%# page import="java.util.*,java.io.*"%>
<%
File f = new File ("E:/PDFfiles/Downloads/" + request.getParameter("file") );
response.setContentType ("application/pdf");
response.setHeader ("Content-Disposition", "attachment; filename=""+request.getParameter("file")+""");
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();
int bit = 256;
int i = 0;
try {
while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
}
}
catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
%>
Source (this is my blog): http://bloggerplugnplay.blogspot.in/2012/05/how-to-create-force-download-link-for.html

<?php
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
}
$reader = fopen($filename, "r");
$contents = fread($reader, filesize($filename));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_end_clean();
echo $contents;

From vb asp net code found on the internet i made this simple c# download.aspx page.
You can use with the file url passed as "f" querystring parameter. (/folder/download.aspx?f=/folder1/example.pdf).
<!DOCTYPE html>
<html>
<head><title></title>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
String strRequest = "";
try
{
strRequest = Request.QueryString["f"].ToString();
}
catch
{ }
if (strRequest.Length > 0)
{
String path = Server.MapPath(strRequest);
System.IO.FileInfo File = new System.IO.FileInfo(path);
if (File.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + File.Name);
Response.AddHeader("Content-Length", File.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(File.FullName);
Response.End();
};
}
}
</script>
</head>
<body></body>
</html>

Related

How to convince chrome(browser) to show the download file dialog?

How to convince chrome(browser) to show the download file dialog while downloading a JSON content?
With the following headers chrome renders the JSON directly on the screen. Content-Type:application/json; charset=utf-8
Any ideas?
As it turns out, you only have to set the content disposition on the server end,
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition: attachment; filename=" + fileName + ".json");

File upload Http client issue Titanium

I am trying to upload a .mp4 file to some server. I am using the HTTP client provided by titanium. when I upload the file, HTTP client is adding some headers in the file due to which the file gets corrupted and cannot be played. When I download the uploaded file and open it in notepad I can see the header which are added to the file.
What should I do so that these headers are not added to the file?
Thanks a lot!
// CODE
var uploadFile = Titanium.Filesystem.getFile(dir, _previewUrl);
var fileUploadUrl = 'Some Url for the server to upload';
var headers = { 'Content-Type' : 'multipart/form-data' };
var content = { 'file' : uploadFile };
var xhr = Titanium.Network.createHTTPClient();
for(var key in _headers) {
xhr.setRequestHeader(key, _headers[key]);
}
xhr.onerror = function(e)
{
Ti.UI.createAlertDialog({title:'Error', message:e.error}).show();
Ti.API.info('IN ERROR ' + e.error);
};
xhr.setTimeout(20000);
xhr.onload = function(e)
{
Ti.UI.createAlertDialog({title:'Success', message:'status code ' + this.status}).show();
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e)
{
ind.value = e.progress ;
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST',fileUploadUrl);
// send the data
xhr.send(content);
// END
try setting the headers after you call xhr.open
// open the client
xhr.open('POST',fileUploadUrl);
for(var key in _headers) {
xhr.setRequestHeader(key, _headers[key]);
}
Do not add { 'Content-Type' : 'multipart/form-data' }; header. This way you should get the file properly without any headers like boundary and file name etc. I could send image, 3gpp file like that successfully But, when I send a video file, my server PHP code $_FILES will be empty array. Even the $_FILES["files"]["error"] have no value. There should some other trick to send video file. (Titanium SDK 3.1.1 & android 4.1.2)
xhr.open("POST", URL);
xhr.send({
files : Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, sourcefilename)
});
}
Try not sending the raw blob itself. Send base64 encoded string instead.
var uploadFile = Titanium.Filesystem.getFile(dir, _previewUrl);
var base64File = Ti.Utils.base64encode(uploadFile.read()).toString();
And try changing the header to
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(base64File);
That will solve your problem.

ASP.NET Optimization - Bundling

I've been trying out the new minification and bundling feature in ASP.NET MVC 4, and it works great as long as you use the default folder conventions for css and js files.
/Content
/Scripts
I usually put css and script in a folder called Static like this
/Static/Css
/Static/Js
I tried to register my own bundles like this:
public static class BundleCollectionExtensions
{
public static void RegisterScriptsAndCss(this BundleCollection bundles)
{
var bootstrapCss = new Bundle("~/Static/Css", new CssMinify());
bootstrapCss.AddDirectory("~/Static/Css", "*.css");
bootstrapCss.AddFile("~/Static/Css/MvcValidation.css");
bootstrapCss.AddFile("~/Static/Css/bootstrap-responsive.min.css");
bootstrapCss.AddFile("~/Static/Css/bootstrap.min.css");
bundles.Add(bootstrapCss);
var bootstrapJs = new Bundle("~/Static/Js", new JsMinify());
bootstrapJs.AddDirectory("~/Static/Js", "*.js");
bootstrapJs.AddFile("~/Static/Js/jquery-1.7.1.min.js");
bootstrapJs.AddFile("~/Static/Js/jquery.validate.min.js");
bootstrapJs.AddFile("~/Static/Js/jquery.validate.unobtrusive.min.js");
bootstrapJs.AddFile("~/Static/Js/bootstrap.min.js");
bootstrapJs.AddFile("~/Static/Js/gunsforhire.js");
bundles.Add(bootstrapJs);
}
}
And in
Global.ascx.cs
I did this:
BundleTable.Bundles.RegisterScriptsAndCss();
The generated markup looks like this:
<link href="/Static/Css?v=D9JdmLZFFwjRwraNKfA1uei_YMoBoqLf-gFc0zHivM41" rel="stylesheet" type="text/css" />
<script src="/Static/Js?v=mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1" type="text/javascript"></script>
However It's doesn't work, the request looks like this:
Request URL:http://localhost:49603/Static/Js?v=mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Request Method:GET
Status Code:301 Moved Permanently (from cache)
Query String Parametersview URL encoded
v:mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Request URL:http://localhost:49603/Static/Js/?v=mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Request Method:GET
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:49603
Referer:http://localhost:49603/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11
Query String Parametersview URL encoded
v:mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Response Headersview source
Cache-Control:private
Content-Length:4757
Content-Type:text/html; charset=utf-8
Date:Thu, 01 Mar 2012 19:05:44 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B? QzpcQENvZGVccGVsbGVccGVsbGVoZW5yaWtzc29uLnNlXHNyY1xXZWJcU3RhdGljXEpzXA==?=
What am I doing wrong?
Update
I think I was finally able to solve this by doing the following:
Removing the AddDirectory calls bootstrapCss.AddDirectory("~/Static/Css", "*.css");
Giving the bundles paths that do not reflect the real directory structure
What you are doing "wrong" is that your bundle path corresponds to a REAL path. As I understand it, when the request for "/Static/Css?v=D9JdmLZFFwjRwraNKfA1uei_YMoBoqLf-gFc0zHivM41" comes in, the routing engine first looks for a physical path. It finds a match with your folder "static" and it tries to find a file in it that matches "Css?v=D9JdmLZFFwjRwraNKfA1uei_YMoBoqLf-gFc0zHivM41". When it can't find one, because it doesn't exist, it gives a 404. (I've also seen an access denied.) When the routing engine can't find a physical file path it then looks to other handlers like bundling and minification to serve up the request.
Anyway I think you've figured it out from your comments but I'm not sure it will be very clear to anyone that finds your question. Simply change your registration from:
var bootstrapCss = new Bundle("~/Static/Css", new CssMinify());
to:
var bootstrapCss = new Bundle("~/bundles/Css", new CssMinify());
If you make that change, your issue will go away, (granted there is no physical path that corresponds to "bundles".
if done this a few days ago and it worked well. i created a folder named Helper and then i created a new class called CssJsBuilder.
my class looks like this:
public static void Initializing()
{
IBundleTransform jstransformer;
IBundleTransform csstransformer;
#if DEBUG
jstransformer = new NoTransform("text/javascript");
csstransformer = new NoTransform("text/css");
#else
jstransformer = new JsMinify();
csstransformer = new CssMinify();
#endif
var bundle = new Bundle("~/Scripts/js", jstransformer);
bundle.AddFile("~/Scripts/jquery-1.6.2.js", true);
bundle.AddFile("~/Scripts/jquery-ui-1.8.11.js", true);
bundle.AddFile("~/Scripts/jquery.validate.unobtrusive.js", true);
bundle.AddFile("~/Scripts/jquery.unobtrusive-ajax.js", true);
bundle.AddFile("~/Scripts/jquery.validate.js", true);
bundle.AddFile("~/Scripts/modernizr-2.0.6-development-only.js", true);
bundle.AddFile("~/Scripts/AjaxLogin.js", true);
bundle.AddFile("~/Scripts/knockout-2.0.0.debug.js", true);
bundle.AddFile("~/Scripts/bootstrap.js", true);
bundle.AddFile("~/Scripts/dungeon.custom.js", true);
BundleTable.Bundles.Add(bundle);
bundle = new Bundle("~/Content/css", csstransformer);
bundle.AddFile("~/Content/bootstrap-responsive.css", true);
bundle.AddFile("~/Content/bootstrap.css", true);
BundleTable.Bundles.Add(bundle);
bundle = new Bundle("~/Content/themes/base/css", csstransformer);
bundle.AddFile("~/Content/themes/base/jquery.ui.core.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.resizable.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.selectable.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.accordion.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.autocomplete.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.button.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.dialog.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.slider.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.tabs.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.datepicker.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.progressbar.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.theme.css", true);
BundleTable.Bundles.Add(bundle);
}
After that. Go to Global.asax:
Remove or comment out BundleTable.Bundles.RegisterTemplateBundles()
Add CssJsBuilder.Initializing() to the Application_Start() Method.
Recreate Project and then start it again.
Hope this works for you, too.
In Global.asax.cs replace
BundleTable.Bundles.RegisterTemplateBundles();
with
BundleTable.Bundles.EnableDefaultBundles();
Here is how it worked for me.
This is simplified version I only use default.aspx file no global.asax (you can us it if you want)
In this example I use 2 directories Content2 and Scripts2
in Content2 I have 2 css files one for class="naziv" and other for class="naziv2"
in Scripts2 there are 2 files one with function f1() definition and other with f2() definition
in /bin directory there should be 3 files:
Microsoft.Web.Infrastructure.dll,
System.Web.Optimization.dll,
WebGrease.dll
<%# Page Title="Home Page" Language="vb" debug="true"%>
<%# Import namespace="System.Web.Optimization" %>
<script runat="server" >
Sub Page_Load(sender As Object, e As EventArgs)
System.Web.Optimization.BundleTable.EnableOptimizations = True ''true will force optimization even if debug=true
Dim siteCssBundle = New StyleBundle("~/Content2/css")
siteCssBundle.IncludeDirectory("~/Content2", "*.css")
BundleTable.Bundles.Add(siteCssBundle)
Dim siteJsBundle = New ScriptBundle("~/Scripts2/js")
siteJsBundle.IncludeDirectory("~/Scripts2", "*.js")
BundleTable.Bundles.Add(siteJsBundle)
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body onload="f1(); f2();">
<%: Styles.Render("~/Content2/css")%>
<%: Scripts.Render("~/Scripts2/js")%>
<br />
<span class="naziv">Span 1</span> <br />
<span class="naziv2">Span 2</span> <br />
</body>
</html>

cross domain ajax file upload

I am using Valums Ajax Uploader (valums.com/ajax-upload) to upload files to a server. It works very well when the requesting URL and serving URL (ajax URL) are on same server but is not working when they are on different server.
Can someone please guide me about the same ?
This is a late post but hope it helps.
In your server-side (e.g php), add header defined like this:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Content-type: application/json');
if(array_key_exists('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', $_SERVER)) {
header('Access-Control-Allow-Headers: ' . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
} else {
header('Access-Control-Allow-Headers: *');
}
if("OPTIONS" == $_SERVER['REQUEST_METHOD']) {
exit(0);
}

pdf report view inside browser

I have created this report using BIRT and phpjavabridge
<?php
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=downloaded.pdf");
require_once("http://127.0.0.1:8080/JavaBridge/java/Java.inc");
header("Content-type: text/html");
// the report file to render
$myReport = "test.rptdesign";
// load resources, .rpt files and images from the current working dir
$here = getcwd();
$ctx = java_context()->getServletContext();
$birtReportEngine = java("org.eclipse.birt.php.birtengine.BirtEngine")->getBirtEngine($ctx);
java_context()->onShutdown(java("org.eclipse.birt.php.birtengine.BirtEngine")->getShutdownHook());
// Create a HTML render context
try{
// Load the report design
$design = $birtReportEngine->openReportDesign("${here}/${myReport}");
$task = $birtReportEngine->createRunAndRenderTask( $design );
$task->setParameterValue("sample", new java("java.lang.String", "Hello world!"));
// Add HTML render options
$options = new java("org.eclipse.birt.report.engine.api.PDFRenderOption");
$options->setOutputFormat($options->OUTPUT_FORMAT_PDF);
// Create the output
$out = new java("java.io.ByteArrayOutputStream");
$options->setOutputStream($out);
$task->setRenderOption($options);
$task->run ();
$task->close();
} catch (JavaException $e) {
echo $e; //"Error Calling BIRT";
}
// Return the generated output to the client
echo java_values($out->toByteArray());
?>
The report viewed perfectly inside Internet Explorer 8.0 as it triggered the Adobe Acrobat plugin. The problem is when I opened the report inside Mozilla Firefox 3.5.4 and Google Chrome 4.0.233 it showed me the binary string content of the pdf file, instead of triggering the Adobe Acrobat plugin.
I have checked this by putting a pdf file in the htdoc folder and call it from Firefox and Chrome, it worked just fine. But why the header wont work for the report?
*Also why the header only work for IE 8.0? I need the report to be viewed in all major browser
Content-type should be "application/pdf"
(or "application/x-pdf", for more recent pdf formats)
I think that if you change
header("Content-type: text/html");
to
header("Content-type: application/pdf");
in the code above, the browsers mentioned should start rendering the pdf documents properly (provided they are so configured), and IE will continue working ok (IE has some Automatic MIME Type Detection (based on the first few hundred bytes of content), which is a mixed blessing...)