Download database file attachments by their real names - laravel

I can't figure out how to get a database file attachment, to be downloaded with is real file name.
My model have many file attachements (many attachOne) and there is no problem to get link to them with
{{ model.myfile.filename }}
What I want to do is to get those files downloaded with their real file name.
I try to define an ajax event handler in my layout like so :
function onDonwload()
{
$path = post('path');
$name = post('name');
// Storage::exists('uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf'); => OK
// Storage::exists($path); =>OK
$path = storage_path().'/app/'. $path;
return Response::download( $path, $name);
}
and
<button data-request="onDonwload"
data-request-data="path: 'uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf', name: 'my real name">
Download
</button>
No missing file error, but get the browser to freeze with an alert that say "A webpage slow down your browser, what do you want to do?".
Did I miss an important point?

You should add separate page for downloading files, Ajax can not help you to download file ( may be it can but process is little complex and long)
create page with /file-download/:id here you can specify any url wit param :id and give it name file-download you can give any name you like for demo i used this name.
In that Page Html section will be Blank and in Page's code section add this code. here you can also check additional security check like user is logged in or not file is of related user or not. for now i am just checking file is related to particular Modal or not.
function onStart() {
$fileId = $this->param('id');
$file = \System\Models\File::find($fileId);
// for security please check attachment_type == your model with namespace
// only then lat use download file other wise user can download all the files by just passing id
if($file && $file->attachment_type == 'Backend\Models\User') { // here add your relation model name space for comparison
$file->output('attachment');
}
else {
echo "Unauthorised.";
}
exit();
}
Generating links, please replace page name with page you created.
<a href="{{ 'file-download'|page({'id': model.myfile.id}) }}" >{{ model.myfile.filename }}</a>
Now, when you click on link file should be downloaded with its original name, and for invalid file id it should show message Unauthorised..
if any doubts please comment.

Related

How to display PDF Documents on the browser using a View in Laravel 5.8

I'm working on a web application using Laravel 5.8, I'm new to Laravel framework. I would like to display PDF documents on the browser when users click on some buttons. I will allow authenticated users to "View" and "Download" the PDF documents.
I have created a Controller and a Route to allow displaying of the documents. I'm however stuck because I have a lot of documents and I don't know how to use a Laravel VIEW to display and download each document individually.
/* PDFController*/
public function view($id)
{
$file = storage_path('app/pdfs/') . $id . '.pdf';
if (file_exists($file)) {
$headers = [
'Content-Type' => 'application/pdf'
];
return response()->download($file, 'Test File', $headers, 'inline');
} else {
abort(404, 'File not found!');
}
}
}
/The Route/
Route::get('/preview-pdf/{id}', 'PDFController#view');
Mateus' answer does a good job describing how to setup your controller function to return the PDF file. I would do something like this in your /routes/web.php file:
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
The other part of your question is how to embed the PDF in your *.blade.php view template. For this, I recommend using PDFObject. This is a dead simple PDF viewer JavaScript package that makes embedding PDFs easy.
If you are using npm, you can run npm install pdfobject -S to install this package. Otherwise, you can serve it from a CDN, or host the script yourself. After including the script, you set it up like this:
HTML:
<div id="pdf-viewer"></div>
JS:
<script>
PDFObject.embed("{{ route('show-pdf', ['id' => 1]) }}", "#pdf-viewer");
</script>
And that's it — super simple! And, in my opinion, it provides a nicer UX for your users than navigating to a page that shows the PDF all by itself. I hope you find this helpful!
UPDATE:
After reading your comments on the other answer, I thought you might find this example particularly useful for what you are trying to do.
According to laravel docs:
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.
All you need to do is pass the file path to the method:
return response()->file($pathToFile);
If you need custom headers:
return response()->file($pathToFile, $headers);
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
Or if file is in public folder
Route::get('/show-pdf', function($id='') {
return response()->file(public_path().'pathtofile.pdf');
})->name('show-pdf');
then show in page using
<embed src="{{ route('show-pdf') }}" type="text/pdf" >

laravel 5.2 carousel only in index page doesn't wok

I use laravel 5.2 and tried to display a carousel only in index page but doesn't work.
I chose that the codes are not "spreaded" on the index page, they are stored in: public/carousel/carousel.php, too(not ...blade.php).
route.php:
Route::get('/', 'HomeController#index')
HomeController.php:
{
$cats = Category::all();
$carousel = public_path('carousel/carousel.php');
//$carousel = storage_path('public/carousel/carousel.php');
return view('layouts.app', compact('cats', 'carousel'));
}
layouts/app.blade.php:
{{-- #include('carousel/carousel');--}}
#if($carousel)
{{ $carousel }}
#endif
#yield('content')
Finally it displays only: C:\wamp\www\app_name\public\carousel/carousel.php.
Can you help me or point to another better way?
In your controller, you are passing to the view a variable called $carousel, which is the path to your file, as you defined here:
$carousel = public_path('carousel/carousel.php');
This is the reason why it only displays the string. You need to get the actual content of the file:
$carousel = file_get_content(public_path('carousel/carousel.php'));
A better and more laravel-ish way to do it would be to rename the file to carousel.blade.php, store it into the resources/views folder and simply include it from your main blade file (without the need of doing anything in the controller):
#include('carousel')
If you need to display the carousel on certain pages only, you can simply pass a variable $carousel = true on the pages that needs to display it:
$carousel = true;
return view('layouts.app',compact('carousel'));
And in your blade view, include the carousel file only when this variables is present and is true:
#includeWhen(isset($carousel) && $carousel, 'carousel')

Download raw data in Joomla component

I have written a Joomla component which is working well. I now want to add a button to an admin list view that when clicked automatically starts a CSV download of only the items selected in the list.
I'm OK with the model logic, the problem I've got is passing the selected cids or presenting raw output without the template.
If I use JToolBar's appendButton function to add a 'Link' type button, then I can send the user to a URL with 'format=raw', but I can't send information about which items were checked.
If I use JToolBarHelper::custom to add a custom list button, then I can send the information about which buttons were checked, but I can't send format=raw
As far as I can see there are two solutions, but I don't know how to implement either of them. Option one would be to force templateless raw output without a URL parameter of format=raw. Option two would be to set a hidden variable with format=raw in the admin form.
Any help would be appreciated
I've solved this as follows:
I added this hidden field to the admin form
<input type="hidden" name="format" value="html" />
Then subclassed JToolbarButtonStandard overriding the _getCommand with
protected function _getCommand($name,$task,$list)
{
JHtml::_('behavior.framework');
$message = JText::_('JLIB_HTML_PLEASE_MAKE_A_SELECTION_FROM_THE_LIST');
$message = addslashes($message);
if ($list)
{
$cmd = "if (document.adminForm.boxchecked.value==0){alert('$message');}else{document.getElementById('adminForm').format.value='raw'; Joomla.submitbutton('$task')}";
}
else
{
$cmd = "document.getElementById('adminForm').format.value='raw'; Joomla.submitbutton('$task')";
}
return $cmd;
}
So that when the button was clicked it changed the format parameter from html to raw.
I'm not going to mark this as solved in case anyone has any better ideas

How to create download link in Laravel

I am having problem creating a download link to download files via a Mobile App from Laravel Storage folder.
I did something like $link = Response::Download(storage_path()./file/example.png) but to no avail.
I moved the file to the public folder and used http://domain.com/file/example.png and asset('file/example.png') but to no avail.
I am getting 404 NOT FOUND ERROR
How do I solve this?
Take a look at the Laravel Helpers documentation: http://laravel.com/docs/4.2/helpers
If you want a link to your asset, you can do it like this:
$download_link = link_to_asset('file/example.png');
Edit
If the above method does not work for you, then you can implement a fairly simple Download route in app/routes.php which looks like this:
Note this example assumes your files are located in app/storage/file/ location
// Download Route
Route::get('download/{filename}', function($filename)
{
// Check if file exists in app/storage/file folder
$file_path = storage_path() .'/file/'. $filename;
if (file_exists($file_path))
{
// Send Download
return Response::download($file_path, $filename, [
'Content-Length: '. filesize($file_path)
]);
}
else
{
// Error
exit('Requested file does not exist on our server!');
}
})
->where('filename', '[A-Za-z0-9\-\_\.]+');
Usage: http://your-domain.com/download/example.png
This will look for a file in: app/storage/file/example.png (if it exists, send the file to browser/client, else it will show error message).
P.S. '[A-Za-z0-9\-\_\.]+ this regular expression ensures user can only request files with name containing A-Z or a-z (letters), 0-9 (numbers), - or _ or . (symbols). Everything else is discarded/ignored. This is a safety / security measure....
Updating answer for Laravel 5.0 and above:
<a href={{ asset('file/thing.png') }}>Thing</a>
You do not need any route or controller.Just give it to anchor tag.
<a href="{{URL::to('/')}}/file/example.png" target="_blank">
<button class="btn"><i class="fa fa-download"></i> Download File</button>
</a>

Help needed on running a MYSQL script in the background of a web page and taking different actions dependent on the result

I have a form on a web page, with one field to enter a code, to search for a property.
On clicking 'submit' I want to be able to run a script in the background without leaving the page.
The script will need to run a MYSQL statement which will have one of these results:
The property code does not exist, so display a Javascript Alert saying it does not exist.
The property is for sale, so call an existing javscript function 'saleSubmit(propertyCode)' to overwrite the exsiting web page with a new page sale.php for that property code
The property is for rent, so call an existing javscript function 'rentSubmit(propertyCode)' to overwrite the exsiting web page with a new page rent.php for that property code
The property is for sale and rent, so display 2 checkboxes within a div on the page to choose either the sales details or the rental details.
Can anybody point me in the right direction here?
Hi Nick - I think I screwed the system up a bit as I initially posted a question, then created an account which would not let me comment on the thread.
The status of the query is as simple as: does not exist, sale, rent, sale & rent
Extra advice would be really appreciated as I am problems googling for examples or a tutorial to point me in the right direction.
I first took this approach when I was looking at this problem to check that the form and Select statement were working correctly. So my form code looked like this:
<form name="idsearch" action="" method="post" onsubmit="xmlhttpPostForm('includes/idsearch-response.php', 'idsearch', 'idSearchResult', '<img src=\'images/loading.gif\'>'); return false;">
<input type="text" id="idRefNo" name="idRefNo" value="Enter Property Code" onfocus="this.value='';" />
GO <input type="image" src="img/template/search2.gif" alt="Click to Search for Properties"/>
and the php code called looked like this:
$idRefNo = $_POST['idRefNo'];
$query = "SELECT DISTINCT * FROM property WHERE property.Title = '".$idRefNo."' AND suspend != 'Yes'"; $result = #mysql_query ($query);
if ($result) { // If the query runs ok
if ($result != "") {
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
if ($row["BaseRental"] > 0 AND $row["Saleprice"] > 0) {
echo 'This property is for RENT and for SALE <br/>';
} else if ($row["BaseRental"] > 0) {
echo 'This property is for RENT only <br/>';
} else if ($row["Saleprice"] > 0) {
echo 'This property is for SALE only <br/>';
} else {
echo 'DOH! What is going on here!!! <br/>';
}
}
As I said above I would appreciate it if you could point me in the right direction to achieve what I want to do at the beginning of this thread.
First of all let's differentiate between the page(client) and your mysql database(server). Your page will have to send some request to your server which triggers a script to query the database. The result of that query is returned as a response to your page.
You could send a request by using javascript and the xmlhttprequest or try jquery which offers very simple methods to make requests ($.ajax(...)).
Your server and the script which queries your db should then return some meaningful status back to your client which has to interprete the result: Doing alerts, showing your div or whatever you'd like to do. I suggest returning the response as json which can be directly used in javascript without any parsing hassle. If the status of your query as simple as: does not exist, sale, rent, sale & rent. You could go as far and encode those as plaintext numbers, no json needed.

Resources