I need convert my json data in file .json. I parsing data to array of json in this code
$movies = Movie::all();
return response()->json($movies);
I need create movies.json file. Where my file must be, which folder? And how to it?
use
use Illuminate\Support\Facades\Storage;
and then
Storage::disk('public')->put('movies.json', response()->json($movies));
and this file will be save in public folder
According to the fact that you want to create the file on the server, maybe you can use the file-storage functions in Laravel like this
use Illuminate\Support\Facades\Storage;
$movies = Movie::all();
Storage::put('Movies.json', $movies);
return true;
In the future, if you want to offer it as a download you can create a response macro. I've done the same for a HTML download
File: App\Providers\AppServiceProvider#boot
\Response::macro('attachment', function ($content) {
$headers = [
'Content-type' => 'text/json',
'Content-Disposition' => "attachment; filename='Movies.json'",
];
return \Response::make($content, 200, $headers);
});
And call it as
return response()->attachment($movies); //App\Providers\AppServiceProvider
in your web.php
Route::get('/download','MoviesController#downloadJSON')->name('download_movies');
paste below code in your controller :
public function downloadJSON(Request $request){
$table = Movie::all();
$filename = "movies.json";
$handle = fopen($filename, 'w+');
fputs($handle, $table->toJson(JSON_PRETTY_PRINT));
fclose($handle);
$headers = array('Content-type'=> 'application/json');
return response()->download($filename,'movies.json',$headers);
}
read more about Response download
Related
I am trying to download multiple images as a zip file but getting errors
Invalid argument supplied for foreach() please help me how i resolve that thanks.
Check the error: https://flareapp.io/share/47qG2A3m
Controller
public function dowloads($id)
{
$url = config('yourstitchart.file_url');
$zip = new ZipArchive;
$inboxFiles = Inbox::where('id', $id)->first()->file;
// $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"
foreach ($inboxFiles as $file) {
$zip->add($url . $file); // update it by your path
}
$zip->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
}
You are returning a string, you can't handle it like an array.
It's JSON, you can just use :
$inboxFiles = json_decode(Inbox::where('id', $id)->first()->file);
(the above code is not really robust, but you have the way)
I know this has already been answered, but do not use json_decode any more in Laravel...
Cast the field file as a JSON/array, so it will automatically be an array and when you save it in the database, it will be transformed to JSON, and when you want to read it back, it will be automatically transformed to array...
To do so, you have to edit Inbox model and add this property:
protected $casts = ['file' => 'array'];
And that's it, then you have to use the field as if it is already an array, so leaving your code as it is in your question, without any edit, it will work right away:
public function dowloads($id)
{
$url = config('yourstitchart.file_url');
$zip = new ZipArchive;
$inboxFiles = Inbox::where('id', $id)->first()->file;
// $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"
foreach ($inboxFiles as $file) {
$zip->add($url . $file); // update it by your path
}
$zip->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
}
I'm trying to return query data and storage Images from laravel controller. My code looks like following :
class ClaimController extends Controller{
.....
public function show(Claim $claim)
{
$front_image = Storage::disk('do_spaces')->get($claim->images->front_image); //image file
$back_image = Storage::disk('do_spaces')->get($claim->images->back_image); //image
// return $front_image [works]
$claim = Claim::all();
//this throws error
return response()->json([
'claim' => $claim,
'images' => [$front_image, $back_image]
]);
}
}
Now I far I understand return->response()->json([]) doesn't send image file. How I can return all data together to frontend app ?
you have the option to return the images from original server which they are stored in or you can return an encoded version of the image as string and in front end reconstruct it.
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
And then use it in front like this :
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
This is the link for second part.
You can use Storage::url()
$st=\Illuminate\Support\Facades\Storage::disk('do_spaces')->url($claim->images->front_image);
dd(url($st));
Storage::url() return image path and then url() will return full url path
"http://127.0.0.1:8000/storage/imagefolder/filename"
Make sure to symbolic link to storage folder by running following command
php artisan storage:link
Also you can do the following without storage url
asset('storage/'.$claim->images->front_image)
I have a file download function that works well on Firefox and Safari, but if I try to download the same file on Chrome or MS Edge, the file is downloaded without an extension.
Here's the function
public function download_chapter_file(Downloadable $downloadable, Request $request): StreamedResponse
{
if (!$request->hasValidSignature()) abort(401);
$headers = ['Content-Type' => 'application/'.$downloadable->type];
return Storage::download($downloadable->path,$downloadable->title,$headers);
}
$downloadable->type is either excel or pdf.
$downloadable->path is the full file path. eg storage/app/public/downloadable/chapters/9/ycCjt0K911x3b1aFjX8i0S9Jj8.pdf
I have tried using
return response()->download(); but it does not solve the problem.
I'd appreciate your help.
try this , it work with me :-
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($downloadable->path,$downloadable->title,$headers);
After hours of trials. I finally got a working solution.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class StorageController extends Controller
{
public function download_chapter_file(Downloadable $downloadable, Request $request):StreamedResponse
{
if (!$request->hasValidSignature()) abort(401);
$extension = File::extension(storage_path('app/'. $downloadable->path));
$filename = $downloadable->title.'.'.$extension;
return Storage::download($downloadable->path,$filename);
}
}
Thank you all for trying
I have build a laravel application where I have some files on public/files directory. if I give this link to others such as download Link, they have chance to know my directory ..
Suppose the link i have to give download link as
www.abc.com/files/45454553535.zip
But i don't want to let Users know that it's there in files directory. So How Do i hide the directory?
Keep your files in the storage directory. That way you can serve the file to the users through code.
Try to follow the documentation: https://laravel.com/docs/5.4/filesystem
I don't know whether this would work or not but giving you an idea. Create a php file use like this:
header('Content-Type: application/zip');
$a=file_get_contents(file.zip)
echo $a;
From this user will not know from where the contents are fetched.
Try this.
public function getDownload()
{
$filename='45454553535.zip'
$file= public_path(). "/files/".$filename;
$headers = array(
'Content-Type: application/zip',
);
return Response::download($file, $filename, $headers);
}
".files/45454553535.zip"will not work as you have to give full physical path.
Update 20/05/2016
Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Response facade. However, my previous answer will work for both Laravel 4 or 5.
return response()->download($file, $filename, $headers);
You can just create a your controller and route.
Route::get('files/{filename}', [
'as' => 'file.get',
'uses' => 'FileController#get',
]);
Controller should check your proper directory. Try to keep your files in storage path, not public.
class FileController extends Controller
{
private $path;
public function __construct()
{
$path = storage_path()
. '/your-valid-directory/';
}
public function get($filename)
{
$file_path = $this->path
. filter_var($filename, FILTER_SANITIZE_STRING);
if (file_exists($file_path) && is_readable($file_path)) {
return response(file_get_contents($file_path), 200, [
'Content-Type: application/zip',
]);
} else {
abort(404);
}
}
}
Now you can get access to specific file by:
{{ route('file.get', ['filename' => '45454553535.zip') }}
This action generate link looks like: your-domain.com/files/45454553535.zip. :)
Anyway in my opinion - in the future just make file factory with specific headers, directories.
Good luck!
In Laravel application I'm trying to achieve a button inside view that can allow user to download file without navigating to any other view or route
Now I have two issues:
(1) below function throwing
The file "/public/download/info.pdf" does not exist
(2) Download button should not navigate user to anywhere and rather just download files on a same view, My current settings, routing a view to '/download'
Here is how Im trying to achieve:
Button:
<i class="icon-download-alt"> </i> Download Brochure
Route :
Route::get('/download', 'HomeController#getDownload');
Controller :
public function getDownload(){
//PDF file is stored under project/public/download/info.pdf
$file="./download/info.pdf";
return Response::download($file);
}
Try this.
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, 'filename.pdf', $headers);
}
"./download/info.pdf"will not work as you have to give full physical path.
Update 20/05/2016
Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Response facade. However, my previous answer will work for both Laravel 4 or 5. (the $header array structure change to associative array =>- the colon after 'Content-Type' was deleted - if we don't do those changes then headers will be added in wrong way: the name of header wil be number started from 0,1,...)
$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'filename.pdf', $headers);
File downloads are super simple in Laravel 5.
As #Ashwani mentioned Laravel 5 allows file downloads with response()->download() to return file for download. We no longer need to mess with any headers. To return a file we simply:
return response()->download(public_path('file_path/from_public_dir.pdf'));
from within the controller.
Reusable Download Route/Controller
Now let's make a reusable file download route and controller so we can server up any file in our public/files directory.
Create the controller:
php artisan make:controller --plain DownloadsController
Create the route in app/Http/routes.php:
Route::get('/download/{file}', 'DownloadsController#download');
Make download method in app/Http/Controllers/DownloadsController:
class DownloadsController extends Controller
{
public function download($file_name) {
$file_path = public_path('files/'.$file_name);
return response()->download($file_path);
}
}
Now simply drops some files in the public/files directory and you can server them up by linking to /download/filename.ext:
File Name // update to your own "filename.ext"
If you pulled in Laravel Collective's Html package you can use the Html facade:
{!! Html::link('download/filename.ext', 'File Name') !!}
In the accepted answer, for Laravel 4 the headers array is constructed incorrectly. Use:
$headers = array(
'Content-Type' => 'application/pdf',
);
Quite a few of these solutions suggest referencing the public_path() of the Laravel application in order to locate the file. Sometimes you'll want to control access to the file or offer real-time monitoring of the file. In this case, you'll want to keep the directory private and limit access by a method in a controller class. The following method should help with this:
public function show(Request $request, File $file) {
// Perform validation/authentication/auditing logic on the request
// Fire off any events or notifiations (if applicable)
return response()->download(storage_path('app/' . $file->location));
}
There are other paths that you could use as well, described on
Laravel's helper functions documentation
While using laravel 5 use this code as you don`t need headers.
return response()->download($pathToFile); .
If you are using Fileentry you can use below function for downloading.
// download file
public function download($fileId){
$entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
$pathToFile=storage_path()."/app/".$entry->filename;
return response()->download($pathToFile);
}
HTML href link click:
<a ="{{ route('download',$name->file) }}"> Download </a>
In controller:
public function download($file){
$file_path = public_path('uploads/cv/'.$file);
return response()->download( $file_path);
}
In route:
Route::get('/download/{file}','Controller#download')->name('download');
I think that you can use
$file= public_path(). "/download/info.pdf";
$headers = array(
'Content-Type: ' . mime_content_type( $file ),
);
With this you be sure that is a pdf.
// Try this to download any file. laravel 5.*
// you need to use facade "use Illuminate\Http\Response;"
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
return response()->download($file);
}
HTML link click
<a class="download" href="{{route('project.download',$post->id)}}">DOWNLOAD</a>
// Route
Route::group(['middleware'=>['auth']], function(){
Route::get('file-download/{id}', 'PostController#downloadproject')->name('project.download');
});
public function downloadproject($id) {
$book_cover = Post::where('id', $id)->firstOrFail();
$path = public_path(). '/storage/uploads/zip/'. $book_cover->zip;
return response()->download($path, $book_cover
->original_filename, ['Content-Type' => $book_cover->mime]);
}
This is html part
<a href="{{route('download',$details->report_id)}}" type="button" class="btn btn-primary download" data-report_id="{{$details->report_id}}" >Download</a>
This is Route :
Route::get('/download/{id}', 'users\UserController#getDownload')->name('download')->middleware('auth');
This is function :
public function getDownload(Request $request,$id)
{
$file= public_path(). "/pdf/"; //path of your directory
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file.$pdfName, 'filename.pdf', $headers);
}
you can use simply inside your controller:
return response()->download($filePath);
Happy coding :)
If you want to use the JavaScript download functionality then you can also do
<a onclick="window.open('info.pdf) class="btn btn-large pull-right"><i class="icon-download-alt"> </i> Download Brochure </a>
Also remember to paste the info.pdf file in your public directory of your project