Error Image Upload and Get, Method App\Image::__toString() must not throw an exception, caught Illuminate\Database\Eloquent\JsonEncodingException - database

I am uploading user profile image which is uploading and moved to storage/app/upload/images folder but when I am trying to display that image, below given error occurs.
Method App\Image::__toString() must not throw an exception, caught Illuminate\Database\Eloquent\JsonEncodingException
Here is my controller function for displaying
public function userProfile() {
$image = Image::all();
return view('frontend.layouts.Profile',compact('image'));
}
My view in which I am displaying image
#foreach($image as $images)
<img style="width:210px ; height: 230px " src="/storage/app/upload/images/{{$images->image}}" >
#endforeach

Please Upload your image in Public directory and then try to access that, it will work fine

There are three ways of making an image available to a user:
1. As a public asset
Here the image is made available to everyone. For instance your website logo, or landing page image would be accessed by all. So there is a url to the image that is easily accessed by all. These sort of files would go straight to public/img/ folder.
2. As a protected image available only if specific url is requested
Here user specific images would be accessed by specific people. Think of your members' personal photos that you want to make available only to the member herself or to some specific person. In this case you would store the images in storage/app/public and make a symlink using the artisan command php artisan storage:link You can read more on this here. Assuming that you store your files using random names using str_random() you would then generate urls to your image using the asset() helper like: echo asset('storage/X3jf5j5b2j3n.jpg'); Given that the file names are random, it would be hard to access this image by everyone excepting those who have the url generated using the asset() helper.
3. As a protected image made available using Intervention library
In this case you would first check if user is logged in and then dynamically load the image using Intervention via another protected route. So in your web routes you would first have the user authorization using auth middleware:
Route::group(['middleware' => 'auth'], function () {
Route::get('user', 'UserController#userProfile');
Route::get('images/{image}', 'UserController#serveImage'); // this route serves the image only if user is logged in
});
Then once your have installed Intervention library using composer, our UserController would look like:
use Intervention;
class UserController extends Controller
{
public function userProfile()
{
$images = Image::all();
return view('frontend.layouts.Profile', compact('images'));
}
public function serveImage($image)
{
$filename = storage_path('app/images/'.$image);
return Intervention::make($filename)->response();
}
}
You can see that the image is now being served from the storage folder and not public folder. So this method serveImage() is called only when the route defined earlier for it is authorized. Intervention then works its magic to read the image and send it as a http response.
Your view would change one tad bit to accommodate the new route end point that we defined called images. I assume here that you are storing the filename of the image in db by a field named filename:
#foreach($images as $image)
<img style="width:210px ; height: 230px " src="{{ url('/images/'.$image->filename) }}" >
#endforeach
Note: Do bear in mind that the preferred way to serve images is by using method 2 since it is much faster. You can use method 3 sparingly if you really don't want anyone to even stumble upon the files using the urls.

Related

Where to save user uploaded images in CodeIgniter?

What I want to do is let a user save an image and when they're accessing their accounts I want the image to display.
What I'm currently doing is I'm saving the images in public folder
Store the path to the database
Path: css\img\myPic.jpg
Display the image
<img class="border" src='esc($empInfo['img'])' style="height: 200px; width: 200px">
But since this is a public folder I can't save personal pictures in this folder
I also tried saving the path to writable\uploads\myPic.jpg but no luck
If you look for a manual or a concept , you can also try this:
You must have some folder where you store all personal images
When user needs it, copy the file into Public folder with a random generated 32 character name (GUID type) but with the original extension.
Then feed it to the user in the view.
Once displayed after the view is called you can delete the image from that folder.
As of the the moment. the solution that I got is "copying" the file(in my case it is an image file)from writable/uploads to public using Publish Library.
$publisher = new Publisher(WRITEPATH . 'uploads', FCPATH. 'img/');
$publisher->addPaths([
'img/myPic.jpg',
]);
$publisher->copy(true); // `true` to enable overwrite
Source Path: WRITEPATH . 'uploads'
Destination Path: FCPATH. 'img/'
Source File: img/myPic.jpg
Now you can ref the image in img tags.
Next step should be replacing/deleting the image after use, because this is not gonna be different when you upload the image at public folder. Will try to update if I found a solution
Source: https://codeigniter.com/user_guide/libraries/publisher.html
PS. Feel free to correct me :) I am also new to web developing in general
Part2: I added this to my function. what it does is after copying the image to the public folder I then rename to 'myPic.jpg'. this will solve my previous problem "replacing/deleting the image after use".
$renameFile = rename(FCPATH. 'img/'.$fileName, FCPATH . 'img/'. 'myPic.jpg');
if($renameFile){
return true;
}
else{
return false;
}

Is it possible to serve a templated text file using spark? (java web framework)

I am using spark as the backend to a project I am working on. I noticed that spark has the ability to serve templated html, using a templating engine such as velocity, freemaker, etc.
However, this isn't quite what I want. Instead of serving an html template, I would like to serve a plaintext file, while still allowing me to insert parameters where needed. For context, I am trying to allow the user to download code examples based on the parameters they have supplied.
Does anything like this exist, or do I need to essentially build the desired file's content and return it as a string?
Example of what I am trying to do
// example.java
public class Example {
public static void main(String [] args) {
System.out.println( {{ param }} );
}
}
So this ^ would be the plain text template that I am attempting to serve... "param" would be passed to the backend via http request, and inserted into the file. Then I would serve the file to the frontend.
So, (as mentioned in the comment :), glad it helped) you can serve this content as HTML page (then you can use template manager) containing only this plaintext content only. Only exception will be the extension which will be .html instead of .java if the user saves the file.
You could declare a route whose return type is 'text/plain'
get(Main.API_PUBLIC + "/sourcecode", (req, res) -> {
res.status(200);
res.type("text/plain");
return " /* This will be the code snippet you'll be returning */ ";
});
Another alternative would be putting your source code files into the static files directory and link to them in your html.

Laravel returning a 404 on an image

This should be fairly simple though it is completely stumping me.
I have a backend Laravel installation running on localhost:8000
I have a front end Angular app running on localhost:9001.
I have some 'static' images I have included in my seed data (eg.
'1', 'user.png'), these images are being rendered perfectly in my front end (they are also served from the exact place my image uploads are going).
The URL I am currently serving images from is http://localhost:8000/images/{filename}
I can upload images from the front to the back end and they appear in the DB and the image is being put in the filesystem, I'm populating the correct URL in my front end (as evidenced by the previous URL).
My uploaded images are not being shown.
In my logs I am getting:
[2015-01-20 18:13:49] local.ERROR: NotFoundHttpException Route: http://localhost:8000/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg [] []
[2015-01-20 18:13:49] local.ERROR: exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException'
I tried a method in my routes file, but couldnt see why, when I am already serving some images already?
I have also set all permissions to 755 on my /images folder.
Any ideas?
I'm not sure I follow every bit of multi-system interaction you have going on, but I'd drop back to first HTTP principles.
Try accessing the image URL directly.
http://localhost:8000/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
If the error in your browser (or your logs, if you're not developing with debug set to true) is
local.ERROR: NotFoundHttpException Route: http://localhost:8000/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
This means your web server couldn't find a file at images/j249ae747ce28c317e02f1fb6d0a10c3.jpg, and handed the request to Laravel. This means you need to figure out why your webserver can't see the file.
Assuming you're serving index.php from the public folder
Do you have a public/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg file?
Are you sure? Copy and paste the path into terminal and to a ls public/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg to make sure your brain isn't missing some subtle case issue
Are any errors showing up in your web server's logs (not Laravel's)
Can you create a text/html file in the images folder and serve it? If not, then you may not be pointing your web server at the folder you think you are.
Something like
http://localhost:8000/images/test.txt
http://localhost:8000/images/test.html
Some first principles debugging like that should point you in the right direction.
rm public/storage
php artisan optimize:clear
php artisan storage:link
This worked for me.
The problem is you haven't generated a url for your uploaded image
Try accessing your url like this
http://localhost:8000/storage/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
To generate the above url
Add this method \Storage::disk('public')->url(); method in your controller.This method accesses the public disk array which is found in Config\filesystems.php and it generates a url in the following format
http://localhost:8000/storage/images/j249ae747ce28c317e02f1fb6d0a10c3.jpg
For example the method below stores the image in the image folder and generates the url of the image path.
public function uploadImage(Request $request)
{
$request->validate(['image'=>'file|image|max:5000']);
$imageProfile = new ImageProfile();
if($request->hasFile('image') && $request->file('image')->isValid())
{
$image = $request->file('image')->store('images');
$imageProfile->image_profile_url = \Storage::disk('public')->url($image);
$imageProfile->save()
}
return response()->json($imageProfile,200);
}
The code returns a Json response below
{
"id": 13,
"image_profile_url ": "http://127.0.0.1:8000/storage/images/cxlogqdI8aodERsmw74nmEx7BkxkWrnyJLMH7sFj.jpeg",
"updated_at": "2020-01-13 16:27:37",
"created_at": "2020-01-13 16:27:37",
}
Try to copy the url and test it in postman.
Visit the link to learn more about Laravel file storage
Laravel File Storage
Hope it helps.
laravel 8
Controler function
public function store(Request $request)
{
$this->validate($request, [
'site_title' => 'required',
'logo_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$input['logo_image'] = time().'.'.$request->logo_image->getClientOriginalExtension();
$request->logo_image->move(public_path('images'), $input['logo_image']);
$input['site_title'] = $request->site_title;
//dd($input);
Site_settings::create($input);
return back()->with('success','Image Uploaded successfully.');
}
blade view
<td>
<img src="{{ url('/images/').'/'.$site_settings->logo_image ?? '' }}" alt="" width="250px" height="auto">
</td>

how to clear the file name list after fineUploader (3.5) uploads file

I download fine uploader 3.5, created http handler for a file upload function in my little website . the website is done by asp.net ajax and jquery. it runs at IE9. every time I upload a file, there is a list of file names shown below the load button. if I don't want thme, what should I do?
my code is like this:
html: ...
'<tr><td><div id="jquery-wrapped-fine-uploader"></div></td></tr>...
'ajax/jquery:...
'$('#jquery-wrapped-fine-uploader').fineUploader({
'request: { endpoint: 'xxx.ashx' }
'})
'$('#jquery-wrapped-fine-uploader').on("complete",
'function (event, id, fileName, responseJSON) {
' alert("UPLOAD SUCCESS");
' $.ajax({some ajax calls here});
' })
// WHERE TO PUT this TO CLEAR the UPLOADED FILE LIST??? $('#jquery-wrapped-fine-uploader').fineUploader('reset');
XXX.ashx:
'... public void ProcessRequest (HttpContext context) {
'do some http request work..
'context.Response.ContentType = "text/plain";
'context.Response.Write("{\"success\":true}");
'}
My question is:
I want to completely remove the uploaded file list which shows automatically in green color ( or red if they fail), in order to clear them, I tried to put: $('#jquery-wrapped-fine-uploader').fineUploader('reset'); right after .on('complete'), it's not working, also #jquery-wrapped-fine-uploader seems cached all the time. please help on this.
If you don't want to see the file list at all, you should be using FineUploaderBasic mode instead of using FineUploader mode and then removing all elements in the pre-built UI. FineUploaderBasic mode gives you access to the API, options, and callbacks, but assumes you will be creating your own UI. In other words, FineUploaderBasic mode does not create any DOM elements (except the opaque file input element as a child of your button container, if you supply one). This is all explained (in a great amount of detail) in the documentation.
Start here: http://docs.fineuploader.com

CakePHP how to combine process steps

I am developing a system that allows users to download files, but IF they download a file I want to log this action in a special purpose table (MySQL).
I can already generate an icon with a link to appropriate file, but I can't see how I can make the record of the click on the icon to download the file also create the log record.
I am guessing I will have to use a button, and set the action of the button to run ... what? a controller action, a helper function, something else...
It is the last bit that I can't really get my head round. I would appreciate any advice from anyone who may have implemented something similar!
bw
You've got the right idea. Link to a controller action, which will write to the database & log, and will load the file and present it to the user.
Example:
class MyController extends AppController {
// Load the model
public $uses = ('DbTable');
public function get_file() {
// Save the DB record
$this->DbTable->save(...);
// Set the output header for content delivery
// (use the appropriate mime-type for your file)
header('Content-Type: image/jpg');
// Have it download as if it were an attachment
header('Content-Disposition: attachment; filename="filename.jpg"');
// Print out the file contents
echo file_get_contents('/path/to/filename.jpg');
// Prevent any further processing or rendering
exit();
}
}

Resources