Laravel: Can't download the generated file - php

I have a function where I generates excel (.csv) file. Everything is working except download.
So my idea was to download the file automatically in the browser after generating the csv file. When the file was generated we store it in the public folder.
So when I call my function , the function is opening the url: http://127.0.0.1:8000/project/tools/export/exportData and displaying the file instead of downloading it. So for this I need your help! Thank you in advance.
My codes :
public function exportData() {
$size=sizeof($arr);
for($i=0; $i<$size; $i++)
{
fputcsv($fh,$arr[$i]);
}
fclose($fh);
$file="Export.csv";
$headers = array(
'Content-Type: text/csv',
);
return response()->download($file, 'Export.csv', $headers);
}

You can add the content-disposition to your headers to indicate how to handle file:
$headers = [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="filename.csv"',
];
To display the file in the browser instead of downloading it, you would exchange attachment for inline.

Related

How to open the PDF generated in new tab

I have a Leave application project that generates a PDF file.
this is the code that generates the pdf after I click submit.
$id = DB::table('leave')->where('user_id', auth()->user()->id)->max('id');
$data = leave::where('id', $id)->select('*')->get();
$filename = auth()->user()->name." - S - ". "LEAVE - ".$randomString->randomString(8)."-".$request->filing_date.".pdf";
$path = storage_path('app/leave_file/'.$filename);
PDF::loadView('pdf_views.leave_pdf', $data[0])->setPaper('legal')->save($path);
if(file_exists($path)){
DB::table('leave_files')->insert([
'filename' => $filename,
'leave_id' => DB::table('leave')->where('user_id', auth()->user()->id)->max('id'),
]);
}
return redirect()->route('leave')->with('success', "success");
I wonder if I can make the newly generated pdf open in the new tab after I click submit on my leave application. thank you to anyone who can help
According to the Laravel docs this is what you need: https://laravel.com/docs/9.x/responses#file-responses
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Use the Cache Facade, to store the generated pdf temporary.
$uuid = Str::uuid();
return response()->stream(function () use ($uuid) {
echo Cache::remember($uuid, 300, function() {
return 'genertated pdf content'
});
}, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename=%s;', $uuid),
]);
Create a route to access to cached file. Name the route.
Now you can open it in a new tab from you frontend e.g. Generate the route with route('routename', ['param' => 123]) and pass it to your FE with a REST endpoint for example.
window.open(url,'_blank');

Laravel Excel download not working

The problem is the same as described here Laravel Excel Download using Controller
But I just can not believe that there is no method to deal with Excel downloads in Laravel without using another resource. I was already able handle the instant downloads in controller with response() for PDFs.
Mabybe the headers are wrong? My code:
public function getFile($file) {
$path = storage_path('app/excel/exports/' . $file);
$headers = array('Content-Type' => File::mimeType($path));
return response()->download($path, $file, $headers);
}
So the excel file is created and saved correctly in my storage folder (happens before the code above). Then I use an axios.get method to download the file with the function above.
Headers I am getting:
Accept-Ranges:bytes
Cache-Control:public
Connection:keep-alive
Content-Disposition:attachment; filename="test_file.xlsx"
Content-Length:7066
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
But whatever I do or try to change the download just won't start.
You can try with these two headers.
return response()->download($path, $file, [
'Content-Type' => 'application/vnd.ms-excel',
'Content-Disposition' => "attachment; filename='Report.xls'"
]);
Thanks,
I manged to solve it.
It seems to be not possible to solve this with a simple axios.get request to the route. Instead I needed to open the route directly with a link.
Did not work with:
HTML
<button #click="downloadExcel()">Download Table as Excel File</button>
downloadExcel() {
axios.get('/customers/export');
}
Simple solution (instead of just using axios.get):
<a :href="/customers/export"><button>Download Table as Excel File</button></a>
So it would also be possible to open the route after the axios request with:
downloadExcel() {
let newWindow = window.open();
axios.get('/customers/export')
.then(response => {
newWindow.location = 'http://' + window.location.hostname + '/customers/export';
});
}

How to download a file from URL without showing the full path in laravel?

Download link:-
<a href='"+ downloadlink + '/attachment-download/' + $('#employee_ID').val()+'/'+ res[i].file_name +"'>
Route:-
Route::get('/attachment-download/{id}/{filename}', array(
'uses' => 'AttachmentsController#getDownloadAttachments'
));
Attachment Controller:-
public function getDownloadAttachments($id,$filename){
$file="./img/user-icon.png";
$resource = \Employee::WhereCompany()->findOrfail($id);
$path = $this->attachmentsList($resource);
foreach($path as $index => $attachment){
if ($filename == $attachment['file_name']) {
$filePath = $attachment['url'];
}
}
//return \Response::download($file);
return \Response::download($filePath);
}
File URL Output:-
https://zetpayroll.s3.ap-south-1.amazonaws.com/employees/81/Screenshot%20from%202017-04-26%2015%3A07%3A45.png?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI57OFN3HPCBPQZIQ%2F20170612%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20170612T144818Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=59ecc4d11b7ed71bd336531bd7f4ab7c84da6b7424878d6487679c97a8c52ca7
In this, if try to download the file by using a static path like
$file="./img/user-icon.png";
return \Response::download($file);
it is downloaded fine. But not possible to downloading file from AWS URL, Please help me how to down file automatically using URL. Or How to get Path from URL in laravel or PHP.
Thank you.
Using the above function all the files are being downloaded. But while trying to open the files, text, pdf, ... files open (.text, .csv, .pdf..) without problem, but images don't.
$fileContent = file_get_contents($filePath);
$response = response($fileContent, 200, [
'Content-Type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
return $response;

Generate csv file using laravel

I searched in google to generate the csv file from laravel and i have found the following code:
public function download(){
$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre- check=0'
, 'Content-type' => 'text/csv'
, 'Content-Disposition' => 'attachment; filename=galleries.csv'
, 'Expires' => '0'
, 'Pragma' => 'public'
];
$list = User::all()->toArray();
# add headers for each column in the CSV download
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list)
{
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
return Response::stream($callback, 200, $headers);
}
In the above code, i didn't understand
$callback = function() use ($list){...}
will someone please explain me?
Save yourself a world of trouble and use this library: http://www.maatwebsite.nl/laravel-excel/docs
It can convert your data to csv, excel and all other sorts of goodies. It's especially good with larger datasets.
Cause it's all fun and games when you open your csv in the same program on the same OS. But as soon as your client uses Libre, Open or just Office op MS or Mac your world will go to new depths of hell in multiple layers.
This library standardises csv for as far as possible and you will love it.
I've recently discovered the 'league/csv' package - have written a S.O post about my usage (a simple example) here: CSV export in laravel 5 controller

How to download a file with RESTFUL cakePHP 2.3

I am using CakePHP 2.3 and I have two apps on 2 different servers. I am required to download a file from the first server using REST. I have made my applications RestFul and have configured the routes. I am able to post, get, put and delete but I cannot get it done to download the file.
Below is a sample code for a get
public function view($id) {
$object = $this->Imodel->find('first', array('conditions' => array('Imodel.id' => $id), 'contain' => array()));
$this->set(array(
'object' => $object,
'_serialize' => array('object')
));
}
I would appreciate any help to download a file with REST, complying with the Restful architecture that I already have in place.
Edit
After some time, I finally got it to work. In case someone else runs into the same problem, the whole thing was about understanding cakePHP HttpSocket better.
So first on the server where the webservice is registered (where we download the file from), below is my function; its response is a file as explained (here)
public function getpdffile($id = NULL){
$filepath = APP. 'Files/file.pdf'; //path to the file of interest
$this->response->file($filepath);
return $this->response;
}
Since the file was not public (not in webroot), i had to use MediaView. Then after setting this, I'd retrieve it for download using HttpSocket as shown below:
public function download($id = NULL, $fileMine = 'pdf', $fileName = 'file', $download = TRUE){
$httpSocket = new HttpSocket();
$filepath = APP. 'Files/myfile.pdf';
$file = fopen($filepath, 'w');
$httpSocket->setContentResource($file);
$link = MAIN_SERVER."rest_models/getpdffile/".$id.".json";
$httpSocket->get($link);
fclose($file);
$this->response->file($filepath);
return $this->response;
}
What I did there was copy the file to the App folder of my server and render it in a view.
I hope it helps someone :-)
On the server which call the file to download :
$file = file_get_contents(urlwhereyoudownload) ;
And on the server where webservice is register :
header('Content-type: $mimetypeoffile');
header('Content-Disposition: attachment; filename=".$fileName."');
readfile("$pathtofile");exit;

Categories