public function readPDF($file_id)
{
$file_id = SiteHelpers::encrypt_decrypt($file_id, 'd');
$file_details = $this->model->getFileDetails($file_id);
if($file_details){
$file = Storage::url('app/public/course/'.$file_details->course_id.'/'.$file_details->file_name.'.'.$file_details->file_extension);
print_r($file);
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename=document.pdf');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// #readfile($file);
return response()->file($file);
}
}
I have this function to display uploaded pdf file. I removed the former #readfile($file); as it does nothing and displays nothing. I did troubleshoot on my file path ($file) and the resulted url displayed pdf. But when I used latter function return response()->file($file); it displayed error that file doesn't exist but my $file string is correct. Could someone help me with that?
Related
Hello Iam Using pdfCrowd Api to convert to pdf. If i use convertfile To specify view it says path is not not valid? How to Pass view to pdfCrowd's Convertfile Function?
function download() { require('pdfcrowd.php'); $user_id=$this->session->userdata('user_id'); $data = array(); $data['result']=$this->user_data_model->getcertificate($user_id); try { // create an API client instance $client = new Pdfcrowd('username','api');
// convert a web page and store the generated PDF into a $pdf variable $pdf = $client->convertFile('certificate_template'); // set HTTP response headers header("Content-Type: application/pdf"); header("Cache-Control: max-age=0"); header("Accept-Ranges:
none"); header("Content-Disposition: attachment; filename=\"google_com.pdf\""); // send the generated PDF echo $pdf; } catch(PdfcrowdException $why) { echo "Pdfcrowd Error: " . $why; } }
function download() {
require('pdfcrowd.php');
$user_id=$this->session->userdata('user_id');
$data = array();
$data['result']=$this->user_data_model->getcertificate($user_id);
try
{
// create an API client instance
$client = new Pdfcrowd('username','api');
// convert a web page and store the generated PDF into a $pdf variable
$pdf = $client->convertFile('certificate_template');
// set HTTP response headers
header("Content-Type: application/pdf");
header("Cache-Control: max-age=0");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"google_com.pdf\"");
// send the generated PDF
echo $pdf;
}
catch(PdfcrowdException $why)
{
echo "Pdfcrowd Error: " . $why;
}
}
convertFile method accepts local HTML file only, it can't be template.
You have 2 options:
use convertURI with your rendered template instead convertFile
or
render your template to temporary local HTML file and use it in convertFile method
I have been going round and round with this. I have uploads working with the follow:
public function store(Tool $tool)
{
If(Input::hasFile('file')){
$file = Input::file('file');
$name = $file->getClientOriginalName();
$path=Storage::put('public',$file); //Storage::disk('local')->put($name,$file,'public');
$file = new File;
$file->tool_id = $tool->id;
$file->file_name = $name;
$file->path_to_file = $path;
$file->name_on_disk = basename($path);
$file->user_name = \Auth::user()->name;
$file->save();
return back();
}
however when I try to download with:
public function show($filename)
{
$url = Storage::disk('public')->url($filename);
///$file = Storage::disk('public')->get($filename);
return response()->download($url);
}
I get the FileNotFound exception from laravel
However, if I use this instead:
$file = Storage::disk('public')->get($filename);
return response()->download($file);
I get
FileNotFoundException in File.php line 37: The file "use calib;
insert into
notes(tool_id,user_id,note,created_at,updated_at)
VALUES(1,1,'windows server 2008 sucks',now(),now());" does not exist
which is the actual content of the file...
It can obviously find the file. but why wont it download?
Try this:
return response()->download(storage_path("app/public/{$filename}"));
Replace:
$file = Storage::disk('public')->get($filename);
return response()->download($file);
With:
return response()->download(storage_path('app/public/' . $filename));
response()->download() takes a path to a file, not a file content. More information here: https://laravel.com/docs/5.4/responses#file-downloads
If any one still could not find their file even though the file clearly exists then try
return response()->file(storage_path('/app/' . $filename, $headers));
It could be due to a missing directory separator or it isn't stored inside the public folder.
I am trying to upload multiple files but I only get 1 file in return.Below is my code:
public function uploadQuoteItemImage(){
$file=Input::file('filename');
$file_count=count($file);
dd($file_count);
$uploadcount=0;
foreach($file as $f){
$random_name=str_random(8);
$destinationPath='images/';
$extension=$file->getClientOriginalExtension();
$filename=$random_name.'_quote_itm_image.'.$extension;
$byte=File::size($file); //get size of file
$uploadSuccess=Input::file('filename')->move($destinationPath,$filename);
$uploadcount ++;
}
if ($uploadcount == $file_count){
QuoteItemImage::create(array(
'quote_item_id'=>Input::get('quote_item_id'),
'filename'=>$filename,
'filesize'=>$byte
));
return Common::getJsonResponse(true, 'image created', 200);
}
}
Even though I sent 3 files its returning only 1 file. Please help.
so in the form-data of postman you are giving the key attribute as filename for files
in turn it should be filename[] since you are sending array of data
once you set it it works fine .
now you can check in the php code like below
$files = Input::file('filename');
foreach ($files as $one) {
$filename = $one->getClientOriginalName();
$listfilenames[] = $filename;
}
echo $listfilenames
I have a function in Laravel that allows the user to export reports from their application. So far exporting .csv is working fine, though when giving them the option to export out to .xlsx it throws an error about the extension not being valid.
Below is the function that is called for exporting.
public function export($fileName, $data, $fileType) {
$xls = new PHPExcel();
$xls->setActiveSheetIndex(0);
if (count($data) > 0) {
$acols = array_keys($data[0]->toArray());
$xls->getActiveSheet()->fromArray($acols, NULL, 'A1');
$xls->getActiveSheet()->fromArray($data->toArray(), NULL, 'A2');
switch ($fileType) {
case 'csv':
$objWriter = new PHPExcel_Writer_CSV($xls);
break;
case 'xlsx':
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->setOffice2003Compatibility(true);
break;
case 'html':
$objWriter = new PHPExcel_Writer_HTML($xls);
return $objWriter->generateSheetData();
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=$fileName");
header("Content-Transfer-Encoding: binary ");
$objWriter->save('php://output');
return;
}
return Redirect::back();
}
This tampering is due to space/ spaces in your code files which corrupt your data passed into excel. you have to debug every corner file by file to identify if there is any space which is not required. It can be at the start of the file i.e. before
If using linux, this command might help to look for right files
find . "*" | xargs grep -il \ \<\?php >> php.txt
The trick: ob_end_clean. It seems that the buffer does not get properly cleaned up, so there is an extra space added. But by doing this, the file was downloaded and was able to be opened.
ob_end_clean();
Here's the problem
I wanted to convert my data into csv format and download it. everything is fine, until the csv file that i had downloaded and there's a little bug on the file which there will be a space at the first line of the file.
for example
Before force download
"name","age",
"brad pit","40",`
After force download
"name","age",
"brad pit","40",
The csv file that i had downloaded and I try to open wit my excel will appear like this
"name" |age
brad pit|40
I believe that is because of the csv file that i had downloaded appeared an external space line in the first line of the data.
Here's the code
//write csv data
$data = $this->dbutil->csv_from_result($query, $delimiter);
//create random file name
$name = rand().'_salesperson_data_'.date('d-m-y').'.csv';
if ( ! write_file('./csv/'.$name, $data))
{
echo 'Unable to write the CSV file';
}
else
{
//perform download
$file = file_get_contents("./csv/".$name); // Read the file's contents
$filename = 'salesperson_data_'.date('d-m-y').'.csv';
force_download($filename, $file);
}
source of force_download()
if ( ! function_exists('force_download'))
{
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
#include(APPPATH.'config/mimes'.EXT);
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}
}
i thought TRIM will be last solution for me and I try to put any where possible but is stil the same. I couldn't found any solution for this problem. Please help. this stuck me for 2days already.
Thanks in advanced.
I don't know if need to use CSV only, but a good plugin/function that I use is this one: http://codeigniter.com/wiki/Excel_Plugin/
It's works with CodeIgniter Query system for exporting stuff to Excel. I use it a lot and never have problems with it.
try to print on the browser, if you see some extra space then remove.
if the extra is still on the csv file when you download, then this extra space is coming from any of your include file.
when you start writing your code try not to leave some space on the top/bottom of the code.
Use ob_clean(); before writing CSV to remove White spaces.