Laravel, upload image errors - image

I know, that there are many many cases about this theme already, but I looked them through, and could not find desired. Also I noticed that not a lot of the users got their answer.
I am working with Laravel5, and I'm trying to upload a picture. Simple upload, just save any picture in public/img folder.
I have looked up some tutorials and came up with this code:
View form:
<form action="{{URL::to('adminPanel/addImg/done/'.$projectId)}}" method="get" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And the controller code:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$filename = $id;
$file->move($destinationPath);
}
I keep getting this error :
Call to a member function move() on a non-object
And I am sure, that the chosen file is image.
I would appreciate any help
So its done, the main issue was the POST part! Also the file format, but here are the correct code, that adds the image:
form:
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}"> //this part is to make POST method work
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
controller:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$file->move($destinationPath, $id.'.png');
}

I don't know if you are using Laravel 4.2 or 5.0. But..
I recommend you to use illuminate/html - Form class. Try to use POST instead GET to upload files (https://stackoverflow.com/a/15210810/781251, http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 , http://php.net/manual/en/features.file-upload.post-method.php , http://php.net/manual/en/features.file-upload.php)
If Laravel 4.2:
View:
{{ Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) }}
<label for="file">File</label>
{{ Form::file('file') }}
{{ Form::close() }}
Controller:
public function postImage()
{
if( ( $file = Input::file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return Redirect::back();
}
throw new \Exception('Error while upload file');
}
Laravel 5.0
View:
{!! Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) !!}
<label for="file">File</label>
{!! Form::file('file') !!}
{!! Form::close() !!}
Controller:
public function upload(Request $request)
{
if( ( $file = $request->file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return redirect()->back();
}
throw new \Exception('Error while upload file');
}
To create a file with a new name and keep the extension:
$ext = $file->getClientOriginalExtension();
$newName = str_random(20) . '.' . $ext;
$file->move( storage_path('images') , $newName );
Now, you have a new name with the same extension. To validate if your file is an image or..whatever, use Validator.

Try this
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And get the image as
public function postImage(Request $request) {
$image = $request->file("image");

Related

File does not exist (ncjoes/office-converter, laravel)

i was using ncjoes/office-converter, trying to upload .docx and convert it to .pdf, but it occurred error when it converts to .pdf
the error shows NcJoes\OfficeConverter\OfficeConverterException
File does not exist --test.docx
view
<form action="/notes" method="POST" role="form" enctype="multipart/form-data">
#csrf
#method('POST')
<div>
<label for="title">title:</label>
<input id="title" name="title">
</div>
<div>
<label for="topdf">upload:</label>
<input type="file" id="topdf" name="topdf">
</div>
<button type="submit" class="btn-sm btn-primary">add</button>
</form>
controller
public function store(Request $request)
{
$validatedData = $request->validate([
'topdf' => 'required|mimes:docx',
'title'=>'required'
]);
$Name = str_replace(" ","",$request->input('title'));
$FileName = $Name . '.' . $request->topdf->extension();
$request->topdf->move(public_path('pdf'), $FileName);
$converter = new OfficeConverter($FileName);
//$fin=$converter->convertTo('output-file.pdf');
//$fin->move(public_path('pdf'), $FileName);
}
i think $converter = new OfficeConverter($FileName); was wrong, but idk how to fix ;;
First upload the file this way:
$file = $request->file('topdf')->store('pdf');
$path = Storage::path($file);
And then, try to access the file and convert via the $path variable:
$converter = new OfficeConverter($path);

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Upload multiple image for posts in laravel 5.5

I want to know how can I have multiple image in my posts?
Currently I have ImageController which I tried to get images and attach to post_id but the issue of that is if I use that method because I still didn't save my post there will be no id to be attached to images.
Any idea on that?
Please take a look for better understanding:
https://ibb.co/huC1Qw
blade:
<form action="upload" id="upload" enctype="multipart/form-data" method="post">
<div class="row">
<div class="col-md-6"><input type="file" class="form-control" name="files[]" multiple></div>
<div class="col-md-6"><input type="submit" class="btn btn-success" value="Upload now"></div>
</div>
</form>
controller:
public function upload(Request $request) {
$files = $request->file('file');
if (!empty($files)):
foreach($files as $file):
Storage::put($file->getClientOriginalName(), file_get_contents($file));
endforeach
endif;
return \response::json(array('success' => true));
}
route:
Route::post('/upload', 'ImageController#upload');
Approach 1.
Return $request->photos or put them in the session while you are not done yet with post submitting. After it was submitted assign references.
Approach 2.
First, save them in [temp] then move and assign to the post.
Approach 3.
Create a default record in your database, assign images to that record, get the record_id post_id and return to the form that post_id. Then just populate that post with your post_id.
Approach 4.
It is not the good choice to save images in the database, just save them as file and place de reference link in the database, or find them by the id of the folder that has the same id as your post, or beautify links to them ... definitely not by saving them to database. It is my opinion, everyone has to find his/her way for an easy living.
Try this :-
use App\ProductsPhoto; \\ add in top of controller
public function upload(Request $request) {
$product = Product::create($request->all());
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$productsPhotos = new ProductsPhoto;
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$destinationPath = 'images/ProductsPhotos'.'/';
$file->move($destinationPath, $fileName);
$productsPhotos->product_id = $product->id,
$productsPhotos->filename = $fileName;
$productsPhotos->save();
}
}
return 'Upload successful!';
}
Hope it helps!
For upload and display images
if you are using two tables.
upload.blade.php
<form method="post" action="{{ url('/uploads') }}" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" class="inputfile" value="{{ old('arquivo') }}" multiple />
Controller
public function show() {
$images = DB::select('SELECT * FROM table1 INNER JOIN table2 on table1.id = table2.id_file');
return view('index')->with('images', $images);
}
public function upload(yourRequest $request) {
$images = model1::create($request->all());
foreach ($request->files as $file) {
$filename = $file->store('/uploads');
modelFiles::create([
'id_file' => $images->id,
'file' => $filename
]);
}
return redirect()->action('Controller#show')->withInput(Request::only('name'));
}
index.blade.php
#foreach($images as $i)
<div class="item {{ $loop->first ? 'active' : '' }}">
<img src="{{ asset("storage/$i->file") }}" alt="...">
</div>
#endforeach

I Cannot able to pass the id in route file in laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

CLI stopped working error

I get "CLI stopped working" error when i press the upload button.I used the sample code from one of the website to upload file into the database column. I use Laravel 5.2.39. command used: php artisan serve
Code:(Only test version)
Form.blade.php
<form method="post" enctype="multipart/form-data" action="/upload_file">
{{ csrf_field() }}
<input type="file" name="file" />
<input type="submit" name="submit" value="upload" />
</form>
Routes.php
(Not an ideal place to code this but it is only for file upload test purpose)
Route::get('/upload_form', function()
{
$data['files'] = Attachment::get();
return View::make('form', $data);
});
Route::post('/upload_file', function()
{
$rules = array(
'file' => 'required|mimes:doc,docx,pdf',
);
$validator = Validator::make(Request::all(), $rules);
if(Request::hasFile('file'))
{
$f = Request::file('file');
$att = new Attachment;
$att->name = $f->getClientOriginalName();
$att->file = base64_encode(file_get_contents($f->getRealPath()));
$att->mime = $f->getMimeType();
$att->size = $f->getSize();
$att->save();
return Redirect::to('/upload_form');
}
});
Has anyone encountered this issue? Need help.

Resources