Download CSV from serverside to browser in Laravel 4 - php

I'm using Laravel 4 framework, I have a function that creates a csv file called data_78888.csv the number 78888 changes everytime the function is run to generate a csv file. That function returns a string like that : "Download/78888"
The folder where my csv files are created is called "outputs" and is located in my project folder where the app folder is located to, (it is not in the public folder).
What I would like to do is to create a route that points to my Process controller like that :
Route::get('Download/{token}', array('uses' => 'ProcessController#downloadCSV'));
In my controller I would like to send that csv file to the browser to download it , I'm doing like that :
<?php
class ProcessController extends BaseController {
public function downloadCSV($token){
$fileToDownload = "data_".$token.".csv";
$filePath = "outputs/";
return Response::download($filePath, $fileToDownload, array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment;filename="'.$fileToDownload
));
}
}
The issue is that this is not working and I get an html file called 78888.htm and an error on the server.
How can I make this working please?

The path to the file has to include the name and file extension of the file.
So try this;
$fileToDownload = "data_".$token.".csv";
$filePath = base_path() . "outputs/" . $fileToDownload;
return Response::download($filePath, $fileToDownload, array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment;filename="'.$fileToDownload
));
Also make sure the file exists, before downloading.

Related

Files Not Saving to Laravel 9 Public Directory

I'm generating PDF documents on the fly using php-pdftk and saving it to the public directory. Works great locally, but on a production Digital Ocean server, the file won't save to the public directory. In my code below at the ->saveAs..., the 'docs/reg-forms/' are directories within public.
...
$pdf = new Pdf('/docs/ax_reg_form.pdf');
$result = $pdf->fillForm([
'email' => $this->usercar->user->email,
'date' => $this->usercar->created_at,
...
])
->needAppearances()
->saveAs('docs/reg-forms/'.$this->usercar->user->id.'_'.strtolower($this->usercar->user->first_name).'_'.strtolower($this->usercar->user->last_name).'_'.'car_class.pdf');
session()->flash('url', '/docs/reg-forms/'.$this->usercar->user->id.'_'.strtolower($this->usercar->user->first_name).'_'.strtolower($this->usercar->user->last_name).'_'.'car_class.pdf');
return redirect()->route('usercar.show', $this->usercar->id);
try to wrap with public_path helper
public_path('docs/reg-forms/');
and check if the path exists
if (!file_exists(public_path('docs/reg-forms/'))) {
mkdir(public_path('docs/reg-forms/'), 0777, true);
}

load selected pre-existing files in blueimp

I am able to load all the files in a directory using blueimp file uploading plugin.
I just want to select only few of the files using filenames in that.
I know that get method of uploadhandler returns all the files in given directory but is there any way to select only few files?
This is what I have done to get all files..
public function getFile() {
extract($this -> reqData);
require_once ('path/to/UploadHandler.php');
$options = array(
'script_url' => "path to uploadhandler",
'upload_dir' => "xxxxxxx",
'upload_url' => "xxxxxxx",
'type' => 'project_files'
);
$upload_handler = new UploadHandler($options);
exit;
}
Please don't give negative remarks just because my editing is poor.
Thanks everybody...

Symfony & Phantom JS Bundle - Routing Error

I am using this Bundle to convert HTML to PDF files.
The actual conversion works, but I have a problem understanding the routing.
Here is my code:
/**
* #Route("/formulare/selbstauskunft/{keycode}", name="saPrint")
*/
public function saPrintAction(Request $request, $keycode)
{
$em = $this->getDoctrine()->getManager();
$sa = $em->getRepository('AppBundle:Selfinfo')->findOneBy(array(
'keycode' => $keycode,
));
if(count($sa) > 0){
$response = new Response(
$this->get('padam87_rasterize.rasterizer')->rasterize(
$this->renderView('default/formSAPrint.html.twig', array(
'selfinfo' => $sa,
))
),
200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="my.pdf"'
]
);
return $response;
}else{
return new Response("fail");
}
}
The bundle creates 2 files, rasterize-UNIQUEID.html and rasterize-UNIQUEID.pdf. The html file contains the correct output.
After the creation of the html file in /bundles/padam87rasterize/temp/ the second part of the script opens this file via an url call here.
Unfortunately the actual rendered page is a symfony error page, saying:
No route found for GET /bundles/padam87rasterize/temp/rasterize-UNIQUEID.html
What do I have to set in order to render the html file?
I think you actually have to create a separare route to render the html. As far as I can tell the rasterize function generates a pdf from the temporary html file (The key word being temporary).

CakePHP Error: Missing view for Media viewclass

Here is my function to download the uploaded files:
public function download() {
$this->viewClass = 'Media';
$params = array(
'id' => 'article.pdf',
'name' => 'article',
'download' => true,
'extension' => 'pdf',
'path' => WWW_ROOT . DS . 'files' . DS
);
$this->set($params);
}
However calling this function results in the following error message:
Error: Media could not be found.
Error: Create the class Media below in file: src\View\Media.php
Any suggestions what is wrong with my code? Thanks in advance!
Any suggestions what is wrong with my code?
Yes:
Wrong CakePHP Version (3.x) for what you try to use
And even in 2.x Media view is deprecated since 2.3 as the documentation clearly states on top of the page: Deprecated since version 2.3: Use Sending files instead.
Read the documentation!
Taken from the link above:
public function sendFile($id)
{
$file = $this->Attachments->getFile($id);
$this->response->file($file['path']);
// Return response object to prevent controller from trying to render
// a view.
return $this->response;
}
And always put the exact CakePHP version you're using in your question.
Error: Create the class Media below in file: src\View\Media.php
Create file in
Path - src/View/
File Name - media.php

cakephp file download link

I've encountered a problem I'm trying to solve for more than two days now: I've built a Website using cakephp and everything is working just fine but I got stuck when I tried to implement download links to files stored under APP_DIR/someFolder/someFile.zip.
How do I set download links to files inside someFolder? I often stumbled over "Media Views" I tried implementing them but so far I've been unsuccessful.
Besides is there no easier way to make files downloadable?
Media Views is deprecated since version 2.3. You should use Sending files instead.
Check out this minimal example in your controller:
public function download($id) {
$path = $this->YourModel->aMagicFunctionThatReturnsThePathToYourFile($id);
$this->response->file($path, array(
'download' => true,
'name' => 'the name of the file as it should appear on the client\'s computer',
));
return $this->response;
}
The first parameter of $this->response->file is relative to your APP directory. So calling $this->response->file('someFolder' . DS . 'someFile.zip') will download the file APP/someFolder/someFile.zip.
“Sending files” requires at least CakePHP version 2.0. Please also consider taking a look at the Cookbook link above.
If you are running an older version of CakePHP you should use Media Views as you already mentioned in your question. Use this code and refer to Media Views (Cookbook).
Here's the same method for older versions:
public function download($id) {
$this->viewClass = 'Media';
$path = $this->YourModel->aMagicFunctionThatReturnsThePathToYourFile($id);
// in this example $path should hold the filename but a trailing slash
$params = array(
'id' => 'someFile.zip',
'name' => 'the name of the file as it should appear on the client\'s computer',
'download' => true,
'extension' => 'zip',
'path' => $path
);
$this->set($params);
}
Right way to generate download link in CakePHP 3
Place this function in AppController or Write a component and then call from other controllers.
Make sure to change the content-type as per the download file
public function downloadResponse() {
return $this->response
->withHeader('Content-Type', 'application/pdf')
->withHeader('Content-Disposition', 'attachment;')
->withHeader('Cache-Control', 'max-age=0')
->withHeader('Cache-Control', 'max-age=1')
->withHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
->withHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' PDT')
->withHeader('Cache-Control', 'cache, must-revalidate')
->withHeader('Pragma', 'public')
->withFile($filePath, ['download' => true]);
}

Categories