Glide library | image not loading up - laravel

im trying to enable this library for my localhost environment.
http://glide.thephpleague.com/1.0/config/integrations/laravel/
Current Laravel Version 5.5
gd2 is enabled in wamp extensions.
I cant seem to find where the problem is.
Path is ok, image exists on it.
See following code for server config.
$server = ServerFactory::create([
'response' => new LaravelResponseFactory(app('request')),
'source' => $source,
//'cache' => new Filesystem(new Adapter('../storage/app/cache/')),
'cache' => $cache,
'cache_path_prefix' => '.cache',
'base_url' => 'transform-img',
]);
now i use this
return $server->getImageResponse($path, request()->all());
it does not give any error.
when i dd() this, i get this response.
StreamedResponse {#1151 ▼
#callback: Closure {#1177 ▶}
#streamed: false
-headersSent: false
+headers: ResponseHeaderBag {#1176 ▶}
#content: null
#version: "1.0"
#statusCode: 200
#statusText: "OK"
#charset: null
}
Callback Closure:
#callback: Closure {#1252 ▼
class: "League\Glide\Responses\SymfonyResponseFactory"
this: LaravelResponseFactory {#1231 …}
use: {▼
$stream: stream resource #543 ▼
timed_out: false
blocked: true
eof: false
wrapper_type: "plainfile"
stream_type: "STDIO"
mode: "rb"
unread_bytes: 0
seekable: true
uri: "D:\wamp\www\Bankrolla\storage\app/public\.cache/img/logo_no_text.png/32c8e67d979eab40a7ef6d1854f1f7cc"
options: []
}
}
file: "D:\wamp\www\Bankrolla\vendor\league\glide-symfony\src\Responses\SymfonyResponseFactory.php"
line: "48 to 54"
}
as statusCode shows 200 and there is no error for file not found, still it does not load any image but shows a placeholder on browser when i navigate.
What can be the issue. if i try to replace image name with any other random string i get error for image not found. so this means it does find the image. thou it fails to render the image.
I have googled, searched on their github comments, could not find any problem similar as mine.
I only get a blank page/image if i load it directly.
also i looked in to the cache directory, it includes the files and those files dimensions are resized. so i am not sure where it goes wrong even when it generates the cache files.
may be i am missing any point here, if anyone can point me to the right direction would be very helpful.
Update:
Value of $source variable:
Filesystem {#1225 ▼
#adapter: Local {#1226 ▼
#pathSeparator: "\"
#permissionMap: array:2 [▼
"file" => array:2 [▼
"public" => 420
"private" => 384
]
"dir" => array:2 [▼
"public" => 493
"private" => 448
]
]
#writeFlags: 2
-linkHandling: 2
#pathPrefix: "D:\wamp\www\Bankrolla\storage\app/public\"
}
#plugins: []
#config: Config {#1229 ▼
#settings: []
#fallback: null
}
}
Storage Directory in my public directory(its a symbolic link of original storage)
Storage Directory of Laravel
The URL i am calling this from.
{localhostDomainHere}/image/img/logo_no_text.png?w=100&h=100&fit=crop-center

Don't know if you already fixed it. But we encountered the same problem a few days ago. After a long search, we found out that the error is caught by a new line in a config:
So check all your config files for space or newline before openings tag. Otherwise, your response is not a valid response anymore and you will get the empty box.
If it is not a config file you need to check all the files that are loaded on the request.

the path mentioned by $source => put images there. if it is 1.jpg, then call the url server_url/img/1.jpg . img is from your route for the function you posted in question. In my case $source as well as $cache was /storage/app and i put image in it and called the route on that image. Hope this helps you.
Check this
This is my code :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Filesystem\Filesystem;
use League\Glide\Responses\LaravelResponseFactory;
use League\Glide\ServerFactory;
class GlideController extends Controller
{
public function show(Filesystem $filesystem, $path)
{
$server = ServerFactory::create([
'response' => new LaravelResponseFactory(app('request')),
'source' => $filesystem->getDriver(),
'cache' => $filesystem->getDriver(),
'cache_path_prefix' => '.cache',
'base_url' => 'img',
]);
return $server->getImageResponse($path, request()->all());
}
}
route :
Route::get('/img/{path}', 'GlideController#show')->where('path', '.*');
this is the content of my storage/app

Related

Issues in uploading files to digital ocean spaces from laravel

It's almost 48 hours that I'm facing an issue with the files upload to Digital Ocean spaces from laravel and I can't make it work.
I've successfully built a livewire component that handle the multiple upload of images, each image is stored in the laravel local storage.
As on this website we plan to host thousands of different images, we have now decided to use Digital Ocean Spaces as storage disk.
In order to do so, as first I installed league/flysystem-aws-s3-v3 composer package as required.
Than in my config/filesystem.phpI've done the following :
'do_spaces' => [
'driver' => 's3',
'key' => env('DO_SPACES_KEY'),
'secret' => env('DO_SPACES_SECRET'),
'endpoint' => env('DO_SPACES_ENDPOINT'),
'region' => env('DO_SPACES_REGION'),
'bucket' => env('DO_SPACES_BUCKET'),
],
And in my .env the following :
DO_SPACES_KEY=key
DO_SPACES_SECRET=secret
DO_SPACES_ENDPOINT=https://ams3.digitaloceanspaces.com
DO_SPACES_REGION=AMS3
DO_SPACES_BUCKET=bucket_name
In my livewire component, after uploading the image to local storage, for each image I'm dispatching a job(dispatch(new ResizeUploadToDo($pic, $extension));) which is supposed to :
Retrieve the image from local storage
Pass it to Intervention library in order to resize it and apply a watermark.
Upload the manipulated Image to Digital Ocean Spaces
Remove the old image from local storage
This is the code I've written so far in my job handle() method :
public function handle()
{
$path = Storage::disk('local')->path($this->pic->storage_file_path);
$img=Image::make($path);
$img->resize(600, 600);
$folderStructure = Carbon::now()->format('Y') . '/' . Carbon::now()->format('m') . '/' . Carbon::now()->format('d'). '/';
$filename=time().'.'.$this->extension;
Storage::disk('do_spaces')->put($folderStructure . $filename, $img, 'public');
}
The issues that I'm now facing are the following :
If i try to dd($img) right after instanciate it with Intervention
library, i get the following :
Intervention\Image\Image {#1570 ▼ // app\Jobs\Images\ResizeUploadToDo.php:49
#driver: Intervention\Image\Gd\Driver {#1578 ▼
+decoder: Intervention\Image\Gd\Decoder {#1598 ▼
-data: null
}
+encoder: Intervention\Image\Gd\Encoder {#363 ▼
+result: null
+image: null
+format: null
+quality: null
}
}
#core: GdImage {#394 ▼
+size: "600x600"
+trueColor: true
}
#backups: []
+encoded: ""
+mime: "image/png"
+dirname: "C:\Users\Gianmarco\wa\hotelista\storage\app22/12/12"
+basename: "SPcNL5FD3OZV4heHWA103J4n5YU8xOCG1SU7pyMd.png"
+extension: "png"
+filename: "SPcNL5FD3OZV4heHWA103J4n5YU8xOCG1SU7pyMd"
}
To me it seems like the retrieved Image is empty, is it correct? Or how should i do to correctly retrieve the image from local storage?
I've noticed that, If the job runs with queue driver sync, files
get uploaded to Digital Ocean Spaces but they are empty (file size:
0MB); while, if the job runs with queue driver 'database' files are not uploaded at all to Digital Ocean Spaces.
Doea anybody know how to solve this matter?
Hope somebody can help me with it.
Thank you
Add this variable 'url' => env('DO_SPACES_URL') below 'bucket' => env('DO_SPACES_BUCKET'), in filesystems.php.
In your .env put the variable DO_SPACES_URL=https://{your bucket name}.ams3.digitaloceanspaces.com
Upload file like this:
Storage::disk('do_spaces')->put('uploads', $request->file('file'), 'public');

Laravel Http Client cannot attach files contents required

I have been looking for the answer but failed to do so.
The problem is simple, I am trying to make an HTTP request using Illuminate\Support\Facades\Http class as documented here https://laravel.com/docs/8.x/http-client#multi-part-requests.
My code:-
$picture = fopen(public_path('/temp_pass/image.jpeg'),'r');
$response = Http::attach('attachment', $picture)
->withHeaders(['Accept'=>'application/json'])
->post('mydomain.com/item/store',['item_id' => 'my_item_id']);
The picture URL is ok. The domain to send to also ok. Unfortunately, I got this error
A 'contents' key is required
I hope great developers here can help me solve this.
The line Http::attach('attachment', $picture) refers to the following file and method.
Illuminate\Http\Client\PendingRequest.php
public function attach($name, $contents = '', $filename = null, array $headers = [])
A 'contents' key is required occurs when $contents is falsy (empty, null, false, 0, etc.) based on my testing.
In your case, this refers to $picture. You should check that $picture actually contains a file stream as expected. Dump it before the HTTP request to test.
dd($picture);
// stream resource #7 ▼
// timed_out: false
// blocked: true
// eof: false
// wrapper_type: "plainfile"
// stream_type: "STDIO"
// mode: "r"
// unread_bytes: 0
// seekable: true
// uri: "/.../image.jpeg"
// options: []
// }

Laravel's UploadedFile store method's behavior doesn't correspond with Storage::url behavior

So I am having an UploadedFile I want to upload to specific disk 'local'.
// $storedFilePath == "kml/uploadedfile.xml";
$storedFilePath = $request->file->store("kml", "local");
The file is actually uploaded into storage/app/kml/uploadedfile.xml - that is CORRECT, following the config for local disk:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
On the other hand, I need to get the full URL path (relative from project root) to this file. I tried
Storage::disk("local")->url($storedFilePath);
But this gets me /storage/kml/uploadedfile.xml - note the path does miss app/ folder.
One line in Laravel's FilesystemAdapter.php that determines the path is here (function getLocalUrl):
$path = '/storage/'.$path;
Given the fact that $path is starting with kml/ it perfectly makes sense that it doesn't work. My question is, why. Why are these not corresponding and how do I get the full internal (so not public) path?
Ok so it was actually quite simple, yet I believe the documentation about this in Laravel is quite confusing. Laravel is just expecting everyone to have a symlink from public/storage into storage/app/public
They somehow even think that everyone using local disk and method url wants to know the public url, which is quite always true only for public disk.
config/filesystems.php
added 'url'
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'url' => storage_path('app')
],
Works correctly now

Mime type validation not working in Laravel 5.7

I want to validate a .pfx file but it fails all the time.
I tried the following code:
$validacoes = [
'certificado' => 'mimetypes:application/x-pkcs12'
];
but it doesn't work.
if I do
dd($request->file('certificado')->getMimeType())
I get: application/x-pkcs12.
what can be wrong?
For images it does work: image/jpg, image/png, etc.
try this
$validacoes = [
'certificado' => 'mimes:application/x-pkcs12'
];
Here's how it should be according to the docs:
'certificado' => 'mimes:p12,pfx'
I have the exact same problem.
My file:
"certificateFile" => UploadedFile {#5824
-test: false
-originalName: "file.pfx"
-mimeType: "application/x-pkcs12"
-error: 0
#hashName: null
My validation rules:
public function rules()
{
return [
'certificateFile' => 'required|mimetypes:application/x-pkcs12',
'certificatePassword' => 'required'
];
}
Any ideas guys?
Edit: Ok, found an answer in another question (Laravel 5 Mime validation) that might answer our problem.
In this comment (https://stackoverflow.com/a/30023227/2796516) it is explained that Laravel uses the guessExtension to validate our file. And checking the source code of said extension we find:
'application/x-pkcs12' => 'p12',
Which probably means that it only accepts certificate files with the p12 extension, pfx wont work.

Laravel write file stream

I am using guzzle to downlaod file from url and save it into my storage.
So I have a code look like this
$response = $this->client->request('GET', $model->url, [
'stream' => true
]);
$body = $response->getBody();
while (!$body->eof()) {
Storage::append($this->filePath, $body->read(1024));;
}
but when I open the folder where my file is located, I see that the file size is changing and sometimes it is zero. So in the end I am getting a invalid file.
How can I solve this problem?

Resources