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
Related
On my page I am making an invoice that is fully compatible with Livewire. I use this package: https://github.com/LaravelDaily/laravel-invoices to generate my invoice and everything works fine. But their is one problem I ran into. I can't download my PDF with Livewire.
Here is a basic example to generate a PDF and download it:
public function invoice()
{
$customer = new Buyer([
'name' => 'John Doe',
'custom_fields' => [
'email' => 'test#example.com',
],
]);
$item = (new InvoiceItem())->title('Service 1')->pricePerUnit(2);
$invoice = Invoice::make()
->buyer($customer)
->discountByPercent(10)
->taxRate(15)
->shipping(1.99)
->addItem($item);
return $invoice->download();
}
Whenever I click on a button
<a role="button" class="pdf-download cursor-pointer" wire:click="invoice">download</a>
Nothing happens. So the problem is that Livewire doesn't support this download method. And this download method looks like this:
public function download()
{
$this->render();
return new Response($this->output, Response::HTTP_OK, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $this->filename . '"',
'Content-Length' => strlen($this->output),
]);
}
$this->render(); Renders a template in a specific folder
Is their a work around for this? Where I can download my pdf with a template or maybe a different strategy. I allready tried one thing. I stored the invoice into a session, like so:
Session::put('invoice', $invoice);
Session::save();
And in a different controller I have.
if ($invoice = Session::get('invoice')) {
$invoice->download();
}
But that gives me this error:
serialization of 'closure' is not allowed
And I tried some stuff I found here: https://github.com/livewire/livewire/issues/483
But nothing works. Can someone give me a direction on where to look or how to fix this? Thanks!
return response()->streamDownload(function () use($invoice) {
echo $invoice->stream();
}, 'invoice.pdf');
Seems to do the trick.
I want to use Intervention Image library for my Laravel project, so I just installed it via Composer and added this line of code to config/app.php:
Intervention\Image\ImageServiceProvider::class,
And also this line was added to aliases part:
'Image' => Intervention\Image\Facades\Image::class,
Now at my Controller I coded this:
class AdminController extends Controller
{
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath), $filename);
$sizes = ["300","600","900"];
Image::make($file->getRealPath())->resize(300,null,function($constraint){
$constraint->aspectRatio();
})->save(public_path($imagePath . "300_" . $filename));
}
}
But as soon as I fill my form to check if it's work or not, this error message pops up:
Error
Class 'App\Http\Controllers\Admin\Image' not found
Which means this line:
Image::make($file->getRealPath())->resize(300,null,function($constraint){
So why it returns this error while I've included it already in my project ?!
If you know, please let me know... I would really appreciate that.
Thanks
On config/app.php you need to add :
$provides => [
Intervention\Image\ImageServiceProvider::class
],
And,
$aliases => [
'Image' => Intervention\Image\Facades\Image::class
]
Now you can call use Image; on the top on your controller :
use Image;
class AdminController extends Controller
{
// ...
}
While implementing jQuery FileUpload in CodeIgniter everything seems to work, no javascript errors and the files get created in the default folders (chmod'ed 0777), but there are two issues.
1. I can't override the default options on the PHP handler provided by the package. Here is the Controller action I'm using to do so, none of the parameters passed are actually applied, if I dump the options within the UploadHandler I get the default options.
public function fileupload()
{
if ($this->input->is_ajax_request())
{
# load library
$this->load->library('UploadHandler');
# upload file
$upload_handler = new UploadHandler(array(
'upload_dir' => FCPATH.'upload/realty/'.$this->_user->id.'/',
'mkdir_mode' => 0777,
'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
));
}
else
{
redirect('error/page_not_found');
}
}
2. The script is throwing a error when a file finishes uploading :
SyntaxError: Unexpected token {
Here is the response of an example request :
{"files":[{"name":"nebula-ngc-281.jpg","size":590295,"type":"image\/jpeg","url":"http:\/\/test.filipematias.info\/mercadoimobiliario\/admin\/files\/nebula-ngc-281.jpg","thumbnailUrl":"http:\/\/test.filipematias.info\/mercadoimobiliario\/admin\/files\/thumbnail\/nebula-ngc-281.jpg","deleteUrl":"http:\/\/test.filipematias.info\/mercadoimobiliario\/admin\/?file=nebula-ngc-281.jpg","deleteType":"DELETE"}]}{"files":[{"name":"nebula-ngc-281 (1).jpg","size":0,"type":"image\/jpeg","error":"File upload aborted","deleteUrl":"http:\/\/test.filipematias.info\/mercadoimobiliario\/admin\/?file=nebula-ngc-281%20%281%29.jpg","deleteType":"DELETE"}]}
According to this document Creating Libraries check how we can pass the param in library
so it would be:-
$options= array(
'upload_dir' => FCPATH.'upload/realty/'.$this->_user->id.'/',
'mkdir_mode' => 0777,
'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
));
$this->load->library('UploadHandler',$options);
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.
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]);
}