How can I display uploaded image from stored location and I want to carry over the same image name to
<input id = "Picture" type="file" name="Picture" accept="image/*" />
This code is used in Controller.php when upload
$img = $input['Picture'];
$name = $img->getClientOriginalName();
$uploaded = $img->move('public/img', $name);
This is where uploaded image will show in my new.blade.php
<img src="#" id="Image" name="Image" />
And Image name doesn't save original name to mysql, it saved like C:xampp mpphpB7CF.tmp
How can I do to save original name that I Uploaded.
Check below code this is working code.
$file = $request->file('Picture');
$destinationPath = 'public/img/';
$originalFile = $file->getClientOriginalName();
$file->move($destinationPath, $originalFile);
This line $originalFile = $file->getClientOriginalName(); will assign original file name to $originalFile and use this variable name where you insert image in database.
Add below line to display image you have uploaded.
<img src='{{ asset('img/'.$originalFile) }}'>
$path = '';
if ($request->hasFile('Picture')) {
$file = $request->file('Picture');
$path = $file->storeAs(public_path('img'), $imageName);
//or
if (file_put_contents(public_path(img) . $imageName, $file)) {
$path = public_path(img) . $imageName;
}
}
return view('your-view', ['img_path' => $path]);;
and in your new.blade.php
<img src="{{ $img_path }}" id="Image" name="Image" />
In Controller
public function show($name)
{
$extension = File::extension($name);
$path = public_path('storage/' . $name);
if (!File::exists($path)) {abort(404);}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
Route
Route::get('/images/{name}', 'FileController#show');
Index.blade.php
<a href='{{ asset("images/$hire_details->file") }}'>click here to view image</a>
Return path from controller and display :
<img src='{{ asset('img/'.$name) }}'>
Return your $uploaded from controller to view
return view('new',['uploaded'=>$uploaded]);
and then in your view
<img src='{{ asset($uploaded) }}' >
I think you can try this:
use Input;
use Image;
$file = Input::file('Picture');
$imageName = $file->getClientOriginalName();
$imgUpload = Image::make($file)->save(public_path('img/' . $imageName));
<img src="{{ asset('img/'.$imageName) }}">
Note: If you have get error for Image then install package for Image from this link
Related
I created a user table with employee's details, and in my image column I have a file uploaded in its cell. How can I keep old file every time I upload a new file.
my view.blade
<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
<th> {{$employee['image']}}</th>
my controller
if($request->hasfile('image')){
$files = [];
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$files[] = $filename;
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'),$filename);
}
$files = implode("</br>;", $files);
}
$employee->image = $files;
$employee->save();
Just change one line :
$employee->image = $files;
to,
$employee->image = $employee->image . $files;
I know this should be the most basic stuff in the world, but somehow I can't make it work. I have a model Category that has an image field
This is the code the uploads the file
$uploadedFile = $request->file('image');
$fileName = time().$uploadedFile->getClientOriginalName();
$path = $uploadedFile->move(public_path().'/uploads/categories', $fileName);
$category->image = $path;
$category->save();
when I try it out, it actually uploads the image but doesn't show the correct url I want to use the url in a img tag like this
<img src="{{$category->image}}" class="img-fluid"/>
when I print the url I get something like this
"C:\Projects\duars_web\public/uploads/categories\15822290505.png"
which of course wont work on a img tag...any clue on why is that happening? and how to get a proper url to my uploaded file?
Try this:
<img src="{!! asset('images/uploads/categories/logo.svg') !!}" />
You need to insert only your image name with extension in table :
if($request->hasFile('image'))
{
$image = $request->file('image');
$image_name = time().$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/categories');
$image->move($destinationPath, $image_name);
}
$user = new User;
$user->image = $image_name; // Save only file name
// More data
$user->save();
Then on your blade :
<img src="{!! asset($category->image) !!}" class="img-fluid"/>
or
<img src="/uploads/categories/{{ $category->image }}" class="img-fluid"/>
Hope this helps.
After a succesful file upload, my show.blade doesn't seem to find my images to display.
I've already linked the directory and the image uploads directly to the wished directory.
post Controller
public function store(Request $request)
{
/**
* Validation Rules using Validator class
*/
$rules = [
/*'post_id' => 'required|numeric',*/
'title' => 'required|min:3',
'intro' => 'required|min:3',
'content' => 'required|min:3',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()) {
// dd('validation fail');
return Redirect::back()
->withInput()
->with(
[
'notification' =>'danger',
'message' => 'Something went wrong'
]
)
->withErrors($validator);
}
$post = new Post();
$post->title = $request->input('title');
$post->intro = $request->input('intro');
$post->content = $request->input('content');
$success = $post->save();
/**
* Handle image upload
*/
if($request->hasfile('image') && $success){
$directory = '/post-' . $post->id;
foreach($request->file('image') as $image) {
$name = $image->getClientOriginalName();
$extension = $image ->getClientOriginalExtension();
$fileName = pathinfo($name,PATHINFO_FILENAME) . '-' . time() . '.' . $extension;
$image->storeAs($directory,$fileName,'public');
$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $directory;
$image->save();
}
return back()->with([
'notification' => 'succes',
'message' => 'You have created a new post'
]);
}
}
Show blade
#extends('layout')
#section('content')
<div>
<h1 class="title">{{$post->title}}</h1>
<p> {{$post->content}} </p>
<div class="row">
#foreach($post->images as $image)
<div class="col-sm">
<img class="img-fluid" src="{{ asset($image->filepath . '/' . $image->filename) }}" alt="{{ $post->title }}">
</div>
#endforeach
</div>
</div>
<p>Edit</p>
#endsection
when i inspect the element, i get the image's alt which is the $post-> title, but the path seems to be incorrect for some reason.
storeAs function returns path to the stored file relative to the storage. You don't need to concatenate it yourself. Also it can be a problem with a forward slash in the path.
// Store result path to the variable
$path = $image->storeAs($directory,$fileName,'public');
$image = new Image();
$image->post_id = $post->id;
$image->filename = $fileName;
$image->filepath = $path; // Save path returned by the storeAs
$image->save();
Use asset with just that path.
<img class="img-fluid" src="{{ asset($image->filepath) }}" alt="{{ $post->title }}">
Also check your file system configuration. public/storage should be symbolic link to the storage/app/public, otherwise stored files will not be accessible from the web.
give this a try.
<img class="img-fluid" src="src="{{ asset('path/to/image/'. $image->filename) }}"" alt="{{ $post->title }}">
I will rather approve it this way
Get the last inserted post ID
$post_id = post->id;
$image = $request->file('image');
if ($request->hasFile('image'))
{
foreach ($request->image as $img) {
$name = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$fileName = $name . '-' . time() . '.' . $extension;
if (!file_exists('POST/IMAGE')) //Let check if the path doesn't exist
{
mkdir('POST/IMAGE', 0777 , true);// then create one with read/write permission
}
$image->move('POST/IMAGE',$imagename); // Save the file in this folder
}else {
$imagename = 'dafault.png'; // Optional: if none file selected, the use default file.
}
$image = new Image();
$image->post_id = $post_idid;
$image->filename = $fileName;
//$image->filepath = $directory;// You don't really need the save the file name in your DB
$image->save();
}
return back()->with([
'notification' => 'succes',
'message' => 'You have created a new post'
]);
}
I'm currently learning laravel and I'm stuck at uploading image gallery & header image to a specific folder. This is my controller code: (I'm uploading images on "edit" page)
public function update(Request $request, $id)
{
$findObject = Accommodation::find($id);
$findObject->update($request->all());
Gallery::destroy('objects_id', $id);
foreach ($request['img'] as $img) {
$gallery = new Gallery();
$gallery->objects_id=$id;
$gallery->img=$img;
$gallery->save();
$file[0] = $request->file;
$name = time() . $file[0]->getClientOriginalName(); // prepend the time (integer) to the original file name
$file[0]->move('uploads', $name); // move it to the 'uploads' directory (public/uploads)
// // create instance of Intervention Image
$img = Image::make('uploads/'.$name)->resize(300,200);
$img->save(public_path().'/uploads/'.$name);
}
And this is my view for uploading gallery & header image:
<div class="form-group">
<label for="exampleInputFile">Index image:</label>
<input type="file" name="headerImage" value="{{$object->headerImage}}">
<img src="{{asset('FrontAssets/img/smjestaj/')}}/{{$object->headerImage}}" style="width: 100px;">
<p class="help-block">Image that will be displayed on index page.</p>
<div class="form-group">
<label for="exampleInputFile">Image gallery</label>
<input type="file" name="img[]" multiple>
<p class="help-block">Choose x images for that will be displayed on gallery page.</p>
And it displays me this error:
Call to a member function getClientOriginalName() on null
Note: I have "enctype="multipart/form-data" in my form.
This is what I get when i do dd();
I hope I described my problem correctly, if I need to add anything else please let me know. Thanks in advance!
As per your html
<input type="file" name="headerImage" value="{{$object->headerImage}}">
and
<input type="file" name="img[]" multiple>
Try changing
From
foreach ($request['img'] as $img) {
$gallery = new Gallery();
$gallery->objects_id=$id;
$gallery->img=$img;
$gallery->save();
$file[0] = $request->file;
$name = time() . $file[0]->getClientOriginalName(); // prepend the time (integer) to the original file name
$file[0]->move('uploads', $name); // move it to the 'uploads' directory (public/uploads)
// // create instance of Intervention Image
$img = Image::make('uploads/'.$name)->resize(300,200);
$img->save(public_path().'/uploads/'.$name);
}
To
if($request->file('img'))
{
foreach ($request->file('img') as $key => $file) {
$gallery = new Gallery();
$gallery->objects_id=$id;
$gallery->img=$file;
$gallery->save();
$name = time() . $file->getClientOriginalName();
$destination = base_path() . '/public/uploads';
$file->move($destination, $name);
}
}
if($request->file('headerImage'))
{
$name = time() . $request->file('headerImage')->getClientOriginalName();
$destination = base_path() . '/public/uploads';
$request->file('headerImage')->move($destination, $name);
}
I have my upload function like this. I can upload the image but i cannot view it the blade.
Controller
public function addProduct()
{
return view('product.add_product');
}
public function saveProduct(Request $request)
{
$details = Input::all();
$product_validation = new Product;
$validation = Validator::make($details,$product_validation->setRules());
$destinationPath = '';
$filename = '';
if (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
}
if($validation->fails())
return Redirect::to('/add_product')->withInput()->withErrors($validation);
else
{
$product = new Product;
$product->product_name = $details['product_name'];
$product->product_description = $details['product_description'];
$product->price = $details['price'];
$product->image = $destinationPath . $filename;
$product->date_uploaded = $details['date_uploaded'];
$product->save();
}
return view('product.add_product');
}
And here's my view
<img src="{{ asset('img/$details->image') }}" alt="{{ $details->product_name }}">
{!! $details->product_name !!}</h2>
{!! $details->price !!}
I know that my image fetching didn't work but how can i do the right code? Hope you can help me guys. Thank you in advance. ^_^
If you are storing you images in your public directory and simply want to return them in your view, I would suggest using $product->image to store the relative path to the file.
i.e. $product->image = '/path/to/folder' . $filename;
You can then simply do this in your blade template by passing $product to the view
Controller
return view('product.add_product', [
'product' => $product,
]);
Blade View
<img src="{{ $product->image }}">