I have searched for the SO and didn't find any article or post related to this.
How do I upload an Image using the Image Intervention and upload a normal file with in a single forum without opening a new page for the uploads.
Hope the below Answer would help someone out there.
Blade
<form action="{{route('index.store')}}" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="resume_path">Resume</label>
<input type="file" class="form-control"
name="resume_path">
</div>
<div class="form-group">
<label for="engineer_avatar">Profile Image</label>
<input type="file" class="form-control"
name="engineer_avatar">
</div>
</form>
Controller
use Image;
use App\Engineers;
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'engineer_avatar' => 'image|mimes:jpeg,png,jpg|max:2048',
'resume_path' => 'file|mimes:doc,docx,pdf|max:2048',
// dimensions:min_width=600,min_height=400'
]);
$engineers = Engineers::findOrFail($id);
if($request->hasFile('engineer_avatar')){
$image = $request->file('engineer_avatar');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/engineer_avatar/' . $filename);
Image::make($image)->resize(600,400)->save($location);
$engineers->avatar_path = $filename;
}
if($request->hasFile('resume_path')){
$file = $request->file('resume_path');
$file_name1 = time() . '.' . $file->getClientOriginalExtension();
$file_path = public_path('resume/engineer/');
$engineers->resume_path = $file_name1;
$file->move($file_path, $file_name1);
$engineers->save();
}
To delete the file ::
public function destroy($id)
{
$engineers = Engineers::findOrFail($id);
unlink(public_path('images/engineer_avatar/' . $engineers->avatar_path ));
unlink(public_path('resume/engineer/' . $engineers->resume_path ));
$engineers->delete();
}
Related
I'm making some kind of form be able to upload PDF file. And I also make a label to preview the file that I'm uploading. But somehow the label wont preview the file with error massage : refused to connect. Can somebody help me with it?
image form preview
So here's the PHP code for the label on the view file that I use :
<div class="form-group row">
<label class="col-md-2 col-form-label">File</label>
<div class="col-md-6">
<input type="file" name="file" id="file" class="form-control" required>
<iframe src="{{ $data['data']['files'] }}" style="width: 1000px; height:500px;" frameborder="0" id="filePreview" class="mt-2"></iframe>
</div>
<small class="text-small">{{ $errors->first('file') }}</small>
</div>
And here is the edit and update controller that I use for that view
public function edit($id)
{
$system = new SystemService();
$systemData = $system->list_badges();
$data['system'] = $systemData['data'];
$api = new SettingService();
$data['data'] = $api->get_about($id);
$data['title'] = 'Ubah Tentang Aplikasi';
$data['default'] = $this->folder;
$data['data_view'] = $this->folder . '/edit';
return view('template', $data);
}
public function update(Request $request, $id)
{
$api = new SettingService();
if ($request->hasFile('file')) {
$file = $request->file('file');
$mime = $file->getClientOriginalExtension();
$filter_file = [
'pdf',
'doc', 'docx',
'csv', 'xls', 'xlsx',
'png', 'jpg', 'jpeg',
];
if (!in_array($mime, $filter_file)) {
return back()->with('failed', 'file extention not correct');
}
$file_path = $request->file('file')->path();
$file_name = md5(date('YmdHis') . $file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$data['file_path'] = $file_path;
$data['file_name'] = $file_name;
}
$result = $api->update_about($id, $data);
if (isset($result['errors'])) {
return redirect($this->folder . '/' . $id . '/edit')->withErrors($result['errors'])->withInput()->with('failed', $result['message']);
}
if ($result['status'] == false) {
return redirect($this->folder . '/' . $id . '/edit')->withInput()->with('failed', $result['message']);
}
return redirect($this->folder)->with('success', $result['message']);
}
Thankyou
i have this code in my controller that can make me upload successfully just one file , and i want to upload many files in once time :
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
$image = new Listingimage();
if ($request->hasFile('image')) {
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
}
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
return redirect()->back();
}
i use also this input :
<form action="{{ route('Listingimages.store', $listing->id) }}" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_method" value="PUT" />
{{csrf_field()}}
{{method_field('PUT')}}
<label> Insert image</label>
<input type="file" name="image" id="files" class="form-control" multiple>
so , how can i upload many files in once time ?
change input name
<input type="file" name="image[]" id="files" class="form-control">
controller
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
if ($request->hasFile('image')) {
foreach($request->file('image') as $file)
{
$image = new Listingimage();
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
}
}
return redirect()->back();
}
This function is the function I use to store a new company:
public function store(Request $request)
{
$file = $request->file('logo');
$filename = 'company-logo-' . time() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('public', $filename);
dd($path);
Company::create([
'name' => $request->name,
'email' => $request->email,
'logo' => $request->logo,
'website' => $request->website
]);
return redirect('/company/all');
}
This view is the one with the form:
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-body">
<h4 class="card-title">Create a Company</h4>
</div>
<div class="container">
<div class="jumbotron">
<ul class="list-group">
<li class="list-group-item">
<h3>Enter Company Information:</h3>
<form action="{{ route('company.store') }}" enctype="mutlipart/form-data" method="POST">
#csrf
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Company name" value="{{ old('name') }}">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input class="form-control" type="file" name="logo">
</div>
<div class="form-group">
<input class="form-control" type="url" name="website" placeholder="Website" value="{{ old('website') }}">
</div>
<button class="btn btn-primary" type="submit">Add Company</button>
</form>
</li>
</ul>
</div>
</div>
</div>
#endsection
This is the route:
Route::post('/add', 'CompaniesController#store')->name('store');
Well, what happens when I try to submit this form is that $file variable always returned with null:
Error
Call to a member function getClientOriginalExtension() on null
http://localhost:8000/company/add
Basically what I want to do is send the name of the image to the database and upload the image to my public folder. Neither happens with this code. when I erase the part starting from $file till dd($path); it adds the values to the database but the image hasn't been uploaded.
Any help? Thanks in advance.
First of all the attribute on the form is wrong which is enctype="mutlipart/form-data" and it should be enctype="multipart/form-data"
or an alternative you can use below code according to your requirements:
if($request->hasFile('logo')){
$file = $request->file('logo');
$fileName = 'company-logo-' .time().$file->getClientOriginalName();
Storage::put('public/'.$fileName,file_get_contents($file));
now you can store the $filename variable in database and image will be uploaded to storage/app/public folder
}
please add use Storage on top of file and run php artisan storage:link to make symbolic link between storage folder and public folder
First you change enctype="multipart/form-data" instead of enctype="mutlipart/form-data" in your form.
Then put this code to your controller
public function store(Request $request)
{
if($request->hasFile('logo')) {
$img_ext = $request->file('logo')->getClientOriginalExtension();
$filename = 'company-logo-' . time() . '.' . $img_ext;
$path = $request->file('logo')->move(public_path(), $filename);//image save public folder
}
//You should store only filename not path in db
Company::create([
'name' => $request->name,
'email' => $request->email,
'logo' => $filename,
'website' => $request->website
]);
return redirect('/company/all');
}
try changing to:
public function store(Request $request)
{
$file = $request->file('logo');
$path = '';
if($file) {
$filename = 'company-logo-' . time() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('public', $filename);
}
Company::create([
'name' => $request->name,
'email' => $request->email,
'logo' => $path,
'website' => $request->website
]);
return redirect('/company/all');
}
if (Input::hasFile('logo')) {
$file = Input::file('logo');
$ext = $file->getClientOriginalExtension();
$file_name = 'company-logo-' . time() . ".{$ext}";
$path = base_path().'/public/';
$file->move($path , $file_name);
}
You can use the file pond. The core library is written in vanilla JavaScript and therefore can be used everywhere. Visit: https://pqina.nl/filepond/
Currently, I have 2 upload forms and 2 functions, uploadImage(); and uploadAlbum();. I have been wondering if I could remove the single image form and use the multi image form for both cases. If only 1 image is selected in the multi image form, a single image would be uploaded and if more than 1 images are uploaded, an album would be uploaded.
That would make the upload view look better since it won't have 2 identical upload forms and it would only require 1 function on the back-end that would determine whether it's a single image or an album based on the amount of images uploaded.
I don't really see any downsides to it but I wanted to make sure before reworking the code.
My upload view:
<form class='uploadForm' action="{{ route('imageUpload') }}" method="POST" enctype="multipart/form-data">
<label for="name">Image Name</label>
<input class='input' type="text" name="name" placeholder="Image Name">
<label for="description">Image Description</label>
<input class='input' type="text" name="description" placeholder="Description">
<input type="file" name="image"> {{ csrf_field() }}
<button class='Submit' type="submit" name="submit">UPLOAD</button>
</form>
<form class='uploadForm' action="{{ route('albumUpload') }}" method="POST" enctype="multipart/form-data">
<label for="albumName">Album Name</label>
<input class='input' type="text" name="albumName" placeholder="Album Name">
<label for="albumDescription">Image Description</label>
<input class='input' type="text" name="albumDescription" placeholder="Description">
<input type="file" name='files[]' multiple> {{ csrf_field() }}
<button class='Submit' type="submit" name="submit">UPLOAD</button>
</form>
My uploadImage() and uploadeAlbum() functions:
public function uploadAlbum(Request $request){
$name = $request['albumName'];
$description = $request['albumDescription'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$files = $request->file('files');
$path = 'storage/uploads/albums/'.$name;
$fileOriginalName = $files[0]->getClientOriginalName();
$fileName = pathinfo($fileOriginalName, PATHINFO_FILENAME);
$extension = $files[0]->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$album = new Album();
$album->name = $name;
$album->description = $description;
$album->user_id = $userId;
$album->thumbnail = $fileNameToStore;
$album->save();
$album->tags()->attach($tag);
if(!File::exists($path)) {
File::makeDirectory(public_path($path));
}
if (is_array($files) || is_object($files)){
foreach ($files as $file){
$fileOriginalName = $file->getClientOriginalName();
$fileName = pathinfo($fileOriginalName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$file->storeAs('public/uploads/albums/'.$name, $fileNameToStore);
$file->storeAs('public/uploads/albums/'.$name.'/thumbnails/', $fileNameToStore);
$thumbnailImage = InterventionImage::make('storage/uploads/albums/'.$name.'/thumbnails/'.$fileNameToStore)->fit(400, 400, function ($constraint) {
$constraint->upsize();
});
$thumbnailImage->save();
$albumImage = new AlbumImage();
$albumImage->file_name = $fileNameToStore;
$albumImage->album_id = $album->id;
$albumImage->save();
}
}
return redirect()->route('albums');
}
public function uploadImage(Request $request){
$this->validate($request, [
'name' => 'required|max:120',
'description' => 'max:120|nullable',
'image' => 'required'
]);
$name = $request['name'];
$description = $request['description'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$file = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($file, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/thumbnails/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/specificImages/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/miniImages/',$fileNameToStore);
$thumbnail = InterventionImage::make('storage/uploads/images/thumbnails/'.$fileNameToStore )->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$thumbnail->save();
$specificImage = InterventionImage::make('storage/uploads/images/specificImages/'.$fileNameToStore )->resize(2000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$specificImage->save();
$miniImage = InterventionImage::make('storage/uploads/images/miniImages/'.$fileNameToStore )->fit(200, 200, function ($constraint) {
$constraint->upsize();
});
$miniImage->save();
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
$image->tags()->attach($tag);
return redirect()->route('home');
}
This is possible of course. You would have to use the field that allows multiple
<input type="file" name="files[]" multiple />
When submitting the form you can check for if the $_POST['files'] array contains only one file. If it does, you can use the logic of a single file (image) and if it contains more you can use the logic of multiple files (album).
When you have this working you can also merge the majority of your logic and split it into multiple functions. One would be called with a foreach.
I am able to store the image in desired location but I am unable to view it.
When the page is reloaded ,the same default image appears .
Default image never changes to my desired Image.
My Controller File(UserController.php):
public function update_avatar(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path('/src/uploads/avatars/' . $filename));
}
return redirect()->route('dashboard');
}
}
My Route file:
Route::post('/dashboard',[
'uses'=>'UserController#update_avatar',
]);
My view File:
<form action="/dashboard" method="post" enctype="multipart/form-data">
<div id="mySidenav" class="sidenav">
×
<input type="file" name="avatar" class="btn btn-sm btn-primary col-md-5" >
<input type="submit" class="pull-right btn btn-sm btn-primary " value="submit">
<input type="hidden" value="{{Session::token() }}" name="_token">
Remove
</div>
<div id="main">
<span style="font-size:30px;cursor:pointer" onclick="openNav()"><img src="download.jpg" class="img-circle img-responsive" alt="Placeholder image"></span>
</div>
</form>
Are you not saving the uploaded Image to the Database? Are you only uploading images to the dedicated Images Folder but not saving it to the Database? If you want, you can do this in your controller:
<?php
public function update_avatar(Request $request){
$avatarURI = null;
if($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path('/src/uploads/avatars/' . $filename));
$avatarURI = "src/uploads/{$filename}";
User::update();
}
// YOU MAY NEED TO PERSIST THIS IN THE DATABASE
// TO UPDATE THE avatar:
$usr = new \App\User();
$usr->update(['avatar' => $avatarURI, 'id'=>$userID]); //<== ID OF THE USER TO BE UPDATED...
return redirect()->route('dashboard', ['imgURI'=>$avatarURI, 'user'=>$usr]);
}
Change user with avatar attribute suit your need
public function update_avatar(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$path = '/src/uploads/avatars/';
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path($path . $filename));
$request->user()->avatar = $filename;
$request->user()->save();
}
return redirect()->route('dashboard');
}