How to send a file to browser for downloading? - download

When client request for a file, I use this code to send it:
public static Result download(String file) {
File file = getRealFile(file);
return Ok(file);
}
But I found the browser will not download it, but display its content instead. The response header:
Content-Type text/plain
Transfer-Encoding chunked
What's the correct way to send a file?
Update
Per Razvi's answer, I found an answer seems good for this question: https://stackoverflow.com/a/1074925/342235
But do we really have to set so many headers?
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filepath");
header("Content-Type: mime/type");
header("Content-Transfer-Encoding: binary");
// UPDATE: Add the below line to show file size during download.
header('Content-Length: ' . filesize($filepath));

You need to set the Content-Disposition header. I believe the value of the header should be attachment. See Manipulating the response doc for this.
For play 2.0 the following works without explicitly setting the header:
ok(new FileInputStream(file))

Related

How to convert a jpg image to base64 with freemarker

I am looking for a way to send a link to an image such as
and converting the base64 binary to a string. It doesn't matter if it's via a function in freemarker or via a Webservice. How can I do this?
Have the solution, just written a php-script:
<?php
header('Content-type: application/json; charset=utf-8');
$link = $_GET['link'];
$imagedata = file_get_contents($link);
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);
print($base64);
?>

How to download files from db in codeigniter

I am creating a resource site for my campus where teachers upload files to folder and reference of that filed stored in db, and students can download those files using download option in student view side, and all these I have done in codeigniter using model view controller.
I need help for coding to download files. I managed to display a set of files but could not download yet, can anyone please help me with this? I'll be so thankful.
Try this
$download_file = 'C:\example.zip';//path of the file
$content_type = mime_content_type($download_file);//mime type of the file
$file_name = basename($download_file);//file name
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: ".$content_type);
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($download_file));
while (ob_get_level()) {
ob_end_clean();
}
readfile($download_file);

Clear the cache before the ajax call

hi everybody i have the following function for ajax call. I need to replace the image with the ajax call image. I need to clear my cache before i call the shownewimage function. Thankyou..
function drawImg(idx)
{
var imp = document.getElementsByName("img_pan");
fn = fnArr[parseInt(idx)];
path = 'designs/' + fn;
$("#img_pan").html('<img id="imgView" src="'+path+'"></img>');
$("#state_info").show();
var url="newimage.php?fn="+path+"&act='getcolors'";
httpRequest("GET", url, shownewimage); // i need to clear cache before the shownewimage function executes.
request.send("");
}
Thing is you can't clear browsers cache from javascript, so what you need to do is to make sure that responses from your server for this newimage.php never get cached.
try this for PHP:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: 0');
Alternatively you could always generate randomized Url like /newimage-12345677, you'd just need the server to map it to the actual php script.

Open PDF in a new tab using dompdf

Im trying to generate pdf using dompdf, how can I open the pdf in a new tab in a browser? Like, I Click A link for the PDF and it should open in a new tab, not save it automatically. I want to give the user a choice to save the file after seeing it first. how do i do that?
whenever i use $pdf->output at the end of the file, it does not change a thing, the file is still downloaded automatically.
please help. thanks.
Whether a PDF is downloaded or viewed in the browser depends on a couple of factors. One is your browser settings, but we have no control there. The second is how dompdf present the PDF to the browser. You can tell dompdf to offer the PDF for direct viewing using $dompdf->stream('my.pdf',array('Attachment'=>0));.
As far as opening in a new tab. That depends on how you are generating the PDF. But the simplest way it to provide a link with a target attribute.
I have a same problem into my site (http://www.pdfwebcreator.com)
My solution is:
$myfile = fopen($strFileName, "r") or die("Unable to open file!");
$fileSize = filesize($strFileName);
header("HTTP/1.1 200 OK");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"temporaryPdf.pdf\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fileSize);
echo fread($myfile, $fileSize);
}
I don't know if you got, but if you use false in this line:
$dompdf-> stream("pasta/doc/relatorio.pdf", array("Attachment" => false));
You can see the pdf in the browser.
Well that you can do with the ->stream(); at the end of the chain.
Example:
//Routes (web.php in case laravel version >= 5.4)
Route::get('/pdf', 'PdfController#pdfStream')->name('pdfStream');
//PdfController.php
public function pdfStream(Request $request) {
$data["info"] = "I is usefull!";
$pdf = PDF::loadView('whateveryourviewname', $data);
return $pdf->stream('whateveryourviewname.pdf');
}
//yourViewPage.blade.php
<a href="{{route("pdfStream")}}" target="_blank" > click me to pdf </a>
Here more information
Am still experimenting, but something like this works fine as well
$pdf->loadView('file/path', compact('values'));
return $pdf->stream();
With this you can add dynamic values to your pdf file page within the browser.

Preventing ajax-jquery loaded external file from caching in IE

I have this jquery script to call an external file. So far so good. The script is working fine, but as always IE makes what he wants. The external file that I load with this script (weather.php) is a file with real-time weather conditions data in it. Whit this script, I can refresh the div inside which is my weather.php file. And obviously I don't want IE to cache the data in this file. I want when someone click on button "REFRESH", the included page to be reloaded with the new data in it. In IE this doesn't happens because of the cache.
How can I change this script to not cache the div's content, or how can I say to my included file (weather.php) to do not cache it self?
This is the script:
function ajax_request() {
$('#column_weather').html('<img src="../images/home/ajax-loader.gif" width="16" height="11" style="vertical-align:middle;"/><b> Loading...</b>');
$('#column_weather').load("../includes/home/weather.php");
}
`
And that's how I call the script:
Refresh`
Put a random variable on your query String
$('#column_weather').load("../includes/home/weather.php?myRand=" + guid());
I would make random var return a guid
function s4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function() guid{
return s4()+s4()+"-"+s4()+"-"+s4()+"-"+s4()+"-"+s4()+s4()+s4();
}
Can't you just have proper caching instructions inside this weather.php file (to say not to cache it)
I would attach the current date and time as a GET parameter. Internet Explorer (and other browsers) view this information as critical to loading the page, just as any function returns a different value with different parameters. The trick is that you don't have to use the parameter. :)
$('#column_weather').load("../includes/home/weather.php?t=" + date());
Adding a random parameter to the end of the query URL will help, but try adding this to the beginning of weather.php:
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
?>

Resources