I am trying to download ai/png from mysql DB but all I get is an empty file.
On the table I only have id and two longblob (file_ai, file_png).
For example, file adobe illustrator view is:
echo CHtml::link('<span class="glyphicon glyphicon glyphicon-download-alt" aria-hidden="true"></span>',
array('User/downloadFile', 'id' => $file->id, 'ext' => 'application/illustrator'),
$htmlOptions = array('class' => 'toolMes', 'download', 'data-toggle' => 'tooltip', 'data-placement' => 'bottom', 'title' => 'Download Ai'));
In the controller:
public function actionDownloadFile($id, $ext) {
$file = Files::model()->findByPk($id);
if ($ext === 'application/illustrator') {
header("Content-length:" . strlen($file->file_ai));
header("Content-type: " . $ext . "");
header('Content-Disposition: attachment; filename="' . $file->id . '_' . date("Y-m-d") . '.ai"');
} else {
header("Content-length:" . strlen($file->file_png));
header("Content-type: image/png");
header('Content-Disposition: attachment; filename="' . $file->id . '_' . date("Y-m-d") . '"');
}
}
Hope it is enough to have your precious suggestions
Your not echoing out the actual file contents!
If you are storing images in your database you need to do the echo after you throw the headers...
echo $file->file_ai;
Related
I'm trying to generate a csv file with PHP and one column contains a cash value. I'd like to add a '£' sign before the number - but everything I have tried, and everything I've found on Stackoverflow doesn't seem to help and the Excel output always has a strange character infront of the £ symbol (see below).
I have pasted some of my code here (I've taken out other rows which were not relevant). Can anyone let me know what I'm doing wrong?
$output = fopen('php://output', 'w');
fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
fputcsv( $output, array('Cash collected'));
$i = 0;
foreach ($quizzes as $key => $value) {
$i++;
$poundsign = html_entity_decode('£', ENT_QUOTES | ENT_XML1, 'utf-8');
$modified_values = array(
$poundsign . $value->quiz_cash,
);
);
fputcsv( $output, $modified_values );
}
fclose($output);
$dest_output = 'output.csv';
$output_size = filesize($dest_output);
header("Content-Type: text/csv; charset=utf-8");
if(isset($_GET['brwry']) || $_GET['brwry'] == NULL):
$filename = '' . $brewerytitle;
else:
$filename = 'All breweries';
endif;
header("Content-Disposition: attachment; filename=\"" . $filename . " " . $_GET['start'] . " - " . $_GET['end'] . ".csv\";" );
header("Content-Length: " . $output_size);
readfile($dest_output);
exit;
Thanks,
Lloyd
Part of what's being displayed:
PKd�wL��� ���/images/image_0.jpg��ex\K��1昙�3�133���;ffff����Ԇ�����w�̼߳�cw��딎�$��Z�������&QRTB�|>��E��M5���|�~b��)�o�3�� �>s���o�'���^B�O��V ����#���Q?S#(�� 6���v4���8����vvV�sy}#�_ �O��s�o���L�7Fv.F&�ol��WV.V��?�����g�W!�/w!�������K�oLL�1`���G�p�X���T�>C�#��L��)q���s��3�g�8�p�O�?
I'm trying to download images into zip file, this is what i've got so far:
if (count($headers->images) > 0) {
$counter = 0;
$zip = new ZipArchive();
$tmpFile = "tmpFolder/tmp" . strtotime("now") . ".zip";
$zip->open($tmpFile, ZipArchive::CREATE);
foreach($headers->images as $key => $images) $zip->addFromString("/images/image_" . $counter++ . ".jpg", file_get_contents($images));
$zip->close();
if (file_exists($tmpFile)) {
$fname = basename($_POST["titleZipFile"] . ".zip");
$size = filesize($tmpFile);
header("Content-Type: archive/zip");
header("Content-Disposition: attachment; filename=$fname");
header("Content-Length: " . $size);
ob_end_clean();
readfile($tmpFile);
//unlink($tmpFile);
echo "<div id='reportMessage'><p>You have successfully save images. Please go to your folder " . $_POST["titleZipFile"] . ".zip<p></div>";
}
}
if I remove the unlink($tmpFile); line then the tmp zip is actually generated and has the images inside the zip. However it's not actually showing the zip downloading in browser.
Does any one have any ideas why this could be happening?
Try to change the header for the content type to the following. I think the header is causing the browser problems with interpreting what it is supposed to do. Try the following type.
header('Content-type: application/zip');
I am trying to save files in the DB using BLOB. I know it is not a very good practice but it needs to be done this way.
Anyway the problem that I am facing is that PDF files returned are not readable anymore. But all other files like docx, odt, txt, jpg and so on are working just fine when converted back from blob.
public function store(Request $request)
{
$data = $request->all();
$file = $request->file('file');
$data['data'] = base64_encode(file_get_contents($file));
$data['extension'] = $file->guessExtension();
$data['name'] = $file->getClientOriginalName();
$file = $this->fileRepo->create($data);
return jsend()->success()
->message("Resource Created Successfully")
->data($file->toArray())
->get();
}
public function download($id)
{
$file = $this->fileRepo->find($id);
$randomDir = md5(time() . $file->id . $file->user->id . str_random());
mkdir(public_path() . '/files/' . $randomDir);
$path = public_path() . '/files/' . $randomDir . '/' . html_entity_decode($file->name);
file_put_contents($path, base64_decode($file->data));
header('Content-Description: File Transfer');
return response()->download($path);
}
Where am I going wrong and is there a special way to store the PDFs in a blob field?
It's possible that the headers are being returned incorrectly and this is causing the file to appear unreadable.
Force them by replacing:
header('Content-Description: File Transfer');
return response()->download($path);
With:
$headers = array(
'Content-Description: File Transfer',
'Content-Type: application/octet-stream',
'Content-Disposition: attachment; filename="' . $file->name . '"',
);
return response()->download($path, $file->name, $headers);
You can set your header return like that. you need to use Laravel's response ie.
public function download($id)
{
$file = $this->fileRepo->find($id);
$randomDir = md5(time() . $file->id . $file->user->id . str_random());
mkdir(public_path() . '/files/' . $randomDir);
$path = public_path() . '/files/' . $randomDir . '/' . html_entity_decode($file->name);
file_put_contents($path, base64_decode($file->data));
return response()->download($path)->header('Content-Description', 'File Transfer');
}
I'm currently making a controller to download files from the server.
It all happens in the index action:
public function indexAction() {
$schuurName = $this->_getParam('storageID');
$fileName = $this->_getParam('fileName');
$name = explode('.', $fileName)[0];
$path = '..' . DIRECTORY_SEPARATOR . 'schuren' . DIRECTORY_SEPARATOR . $schuurName . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($path)) {
$mimeType = mime_content_type($fileName);
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($path));
header('Content-Disposition: attachment; filename=' . $name . ';');
$resource = fopen($path, 'r');
while (!feof($resource)) {
$chunk = fread($resource, 4096);
echo $chunk;
}
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
else {
echo 'file doesn\'t exist';
}
}
So the downloading works right now, I'm testing it with an image of 725 bytes. The problem is.. The image is corrupted so it couldn't be seen/edited. What am I doing wrong in my code?
Thanks!
You should use binary mode. Use the 'rb' flag.
From the php Manual : If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.
http://www.php.net/manual/en/function.fopen.php
I have attached outlook msg file in php application. I am storing that file in sql server database.
Now i want to open and display it from browser.
I tried this code :
if($ext=="msg")
{
header('ContentType : application/octet-stream');
header('Content-Disposition: attachment; filename='. basename($filename));
echo base64_decode($file);
}
$filename and $file are coming from database.
Its opening msg file in outlook from IE and chrome but its not openning from firefox.
Is there any way to make it working in all the browser ?
Or Am i wrong somewhere or is there any setting in browser ?
I had an almost similar situation and was able to solve it.
Include the headers below and it should work just fine.
Regards
header("Pragma: public");
header("Expires: 0");
header('Content-Encoding: UTF-8');
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/vnd.ms-outlook;charset=UTF-8");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=test.msg");
header("Content-Transfer-Encoding: binary ");
#composer require hfig/mapi
# needed if you want to convert to MIME format
#composer require swiftmailer/swiftmailer
require 'vendor/autoload.php';
use Hfig\MAPI;
use Hfig\MAPI\OLE\Pear;
$decodelocation = '/var/html/tmp/';
$baseurl = 'http://example.com/tmp/';
$uniquefolder = uniqid();
// message parsing and file IO are kept separate
$messageFactory = new MAPI\MapiMessageFactory();
$documentFactory = new Pear\DocumentFactory();
$ole = $documentFactory->createFromFile('source-file.msg');
$message = $messageFactory->parseMessage($ole);
$html = preg_replace_callback($this->regex, "utf8replacer", $message->getBodyHTML());
if (count($message->getAttachments()) > 0) {
foreach ($message->getAttachments() as $attach) {
$filename = $attach->getFilename();
$temploc = $decodelocation . '/' . $uniquefolder . '/' . $filename;
$fileurl = $baseurl . '/' . $uniquefolder . '/' . $filename;
$replace_string = get_string_between($html, 'cid:' . $filename, '"');
if ($replace_string) {
file_put_contents($temploc, $attach->getData());
$html = str_replace('cid:' . $filename . $replace_string, base_url($temploc), $html);
} else {
$geturl = array(
'filename' => $filename,
'path' => cencode($temploc),
);
$attachments[] = '<a target="_blank" href="' . $fileurl . '">' . $filename . '</a>';
}
}
}
foreach ($message->getRecipients() as $recipient) {
$email = $recipient->getEmail();
$name = $recipient->getName();
if ($recipient->getType() == 'From') {
$From[] = ($name) ? '' . $name . '' : '' . $email . '';
} elseif ($recipient->getType() == 'To') {
$To[] = ($name) ? '' . $name . '' : '' . $email . '';
} elseif ($recipient->getType() == 'Cc') {
$Cc[] = ($name) ? '' . $name . '' : '' . $email . '';
} elseif ($recipient->getType() == 'Bcc') {
$Bcc[] = ($name) ? '' . $name . '' : '' . $email . '';
}
}
$data = array(
'From' => '' . $message->properties['sender_name'] . '',
'To' => ($To) ? implode('; ', $To) : '',
'Cc' => ($Cc) ? implode('; ', $Cc) : '',
'Bcc' => ($Bcc) ? implode('; ', $Bcc) : '',
'Subject' => $message->properties['subject'],
'hasAttachment' => $message->properties['hasattach'],
'attachments' => ($attachments) ? implode('; ', $attachments) : false,
'html' => $html,
);
#customize your html page using data array. It is take long time for greater than 5 MB.
if($ext=="msg")
{
header("Content-Type: text/Calendar");
header('Content-Disposition: inline; filename='. basename($filename));
echo base64_decode($file);
}