Laravel image uploader - php

I'm trying to do a image upload on a form method but when i'm validating it always return an error saying the file is not an image. here you can see my html image uploader form:
<div class="row form-group">
<h4><strong>Imagen</strong></h4>
<input type="file" id="picture" name="picture" accept=".jpeg,.jpg,.png">
</div>
and my controller where i'm making my validation:
$this->validate(request(),[
'nombre' => 'required|min:5',
'precio' => 'required|numeric',
'descripcion' => 'required|min:10',
'alto' => 'required|numeric',
'ancho' => 'required|numeric',
'largo' => 'required|numeric',
'categoria' => 'required|numeric',
'picture' => 'image|required',
]);
$store = new articulo();
$store->nombre = request('nombre');
$store->categoria_id = request('categoria');
$store->precio = request('precio');
$store->descripcion = request('descripcion');
$store->alto = request('alto');
$store->ancho = request('ancho');
$store->largo = request('largo');
$store->image = request('picture');
$store->save();

For image validation try this:
'picture' => 'mimes:jpeg,jpg,png|required'
You can also add max:5000 file size validation.
Hope that help

To upload an image your form must have the attribute enctype="multipart/form-data" so it submits the image as a file and not a string. Your form should be similar to this:
<form action="/yourroute" method="post" enctype="multipart/form-data">
....
<div class="row form-group">
<h4><strong>Imagen</strong></h4>
<input type="file" id="picture" name="picture" accept=".jpeg,.jpg,.png">
</div>
....
</form>

Related

Get method not supported, use post

I'm getting the error when I try to create a post and I don't know how to fix it since I just began using laravel and I'm still a noobie.
Route (web.php)
Route::put('/create_action', [App\Http\Controllers\ActionController::class, 'createAction'])->name('auditor.create_action');
This is my controller method:
public function createAction(Request $request) {
$sectors = \DB::table('sector')->get();
$risicosoorten = \DB::table('risicosoort')->get();
$risicoclassificaties = \DB::table('risicoclassificatie')->get();
$users = \DB::table('users')->where('name')->get();
$statussen = \DB::table('status')->get();
return view('auditor.create_action' , [
'sectors' => $sectors,
'risicosoorten' => $risicosoorten,
'risicoclassificaties' => $risicoclassificaties,
'users' => $users,
'statussen' => $statussen
]);
$actie->create([
'create_date' => $req->create_date,
'bron_detail' => $req->bron_detail,
'audit_oordel' => $req->audit_oordel,
'process' => $req->process,
'nummer_bevinding' => $req->nummer_bevinding,
'omschrijving_bevinding' => $req->omschrijving_bevinding,
'probleem' => $req->probleem,
'risico_beschrijving' => $req->risico_beschrijving,
'oorzaak' => $req->oorzaak,
'aanbeveling_ia' => $req->aanbeveling_ia,
'map' => $req->map,
'datum_deadline' => $req->datum_deadline,
'datum_bijgesteld' => $req->datum_bijgesteld,
'datum_gesloten' => $req->datum_gesloten,
'voortgang' => $req->voortgang,
'aantekeningen_ia' => $req->aantekeningen_ia,
'oordeel_ia' => $req->oordeel_ia,
'sector' => $req->sector,
'pr' => $req->pr,
'sr' => $req->sr,
'arc' => $req->arc,
'orc' => $req->orc,
'grc' => $req->grc,
'status' => $req->status,
'sub_status' => $req->sub_status
]);
}
my blade file with the form:
#extends('layouts.master')
#section('title')
#endsection
#section('content')
<div class="create_action" id="post">
<form action="{{ route('auditor.create_action') }}" method="POST">
#method('PUT')
#csrf
<form>
<div class="form-group">
<label for="creation_date">Datum ontstaan actie</label>
<input type="date" class="form-control" name="create_date">
</div>
<div class="form-group">
<label for="bron_detail">Bron detail</label>
<input type="text" class="form-control" name="bron_detail">
</div>
<button type="submit" class="btn btn-primary" name="submitBtn" value="submitPost"><strong>Maak actie aan</strong></button>
#endsection
and wayy more form input fields but trying to keep it as short as possible!
You have two opening form tags in your view. Right after the #csrf directive. Is this intentional? Because you can not nest form tags.
This may be what is causing your error because the application is trying to use the 'Get' method for the inner form tag since no method was stated.

Inserting photo and get photo

Hi i want to make it possible when user sign up default photo upload in my DB right now i'm upload it but i don't know if its correct or not here its the code:
<?php
require_once 'includes/header.php';
$profile_pic = basename('files/img/default.jpg');
if (Input::exists()) {
//also here we check our token to see if input
if (Token::check(Input::get('token'))) {
//new instance
$validate = new Validate();
//now here we check our validation with check method
//fist of all we check if its POST then:
$validation = $validate->check($_POST,array(
//contain all rulles we want
//first of all in username as we set in our DB
'username' => array(
//its required
'required' => true,
//minimum character 2
'min' => 2,
//maximum character 20
'max' => 20,
//and we want it unique on users table
'unique' => 'users'
),
'name' => array(
'required' => true,
//minimum character 2
'min' => 2,
//maximum character 20
'max' => 50,
),
'email' => array(
'required' => true,
//minimum character 2
'min' => 10,
//maximum character 20
'max' => 50,
),
'password' => array(
'required' => true,
//minimum character 2
'min' => 6,
),
'SecondPassword' => array(
'required' => true,
//check for be match with password1
'matches' => 'password'
),
));
//is passed
if($validation->passed()){
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username') ,
'name' => Input::get('name') ,
'email' => Input::get('email') ,
'password' => Hash::make(Input::get('password'),$salt) ,
'salt' => $salt,
'joined' => date('Y-m-d H:i:s') ,
'lastlogin' => date('Y-m-d H:i:s'),
'avatar' => $profile_pic
));
Session::flash('home','<span class="success-sign">Thank you for your
regsiteration Please log in</span> ');
Redirect::to('index.php');
} catch (Exception $e) {
die($e->getMessage());
}
}else {
//if error
foreach ($validation->errors() as $error) {
echo "<span class='error-sign'>$error</span><br>";
}
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<label for="username" class='field-name'>Username</label><br>
<!--here in value we declare it to use get method from Input class to get
username for when we see error we dont miss this value and also for name -->
<input type="text" name="username" id="username"
value="<?php echo Input::get('username');?>" autocomplete="off"
onBlur ='checkUser(this)' class='signup'>
<span id='info'></span>
<br>
<label for="name" class='field-name'>Your name</label><br>
<input type="text" name="name"
value="<?php echo Input::get('name');?>" id="name" class='signup' >
<br>
<label for="email" class='field-name'>Your Email</label><br>
<input type='email' name='email' id="email" value="<?php echo
Input::get('email'); ?>"
class='signup'><br>
<label for="password1" class='field-name'>Password</label><br>
<input type="password" name="password" id="password" class='signup'>
<br>
<label for="secondpassword" class='field-name-re'>Retype Password</label>
<br>
<input type="password" name="SecondPassword" id="SecondPassword"
class='signup'>
<br>
<!--this is for token value-->
<input type="hidden" name="token" value="<?php echo Token::generate();?>">
<br>
<span class='fieldname'> </span>
<input type="submit" value="SignUp" class='info-signup'>
</form>
<br>
now as i said i see that in my DB the default.jpg is exists when user sign up but first i don't know if its photo or just name of photo and second i cant show this photo in user profile page
You Never want to actually save an Image's actual data into the database.
With that being said, your code stores the Path name into the database like how it should have been done.
Double check if you are using the correct path.
use
<img src="<?php echo $your_avatar_url; ?> />
to output your image.
look into How to have user upload the image here
http://www.w3schools.com/php/php_file_upload.asp
You need to actually save POSTed photo. Check out move_uploaded_file function.

Image file not properly stored in Mysql database with Laravel

Here i try to store the user's image in the db when they upload it in the form , When they upload it the image is getting stored in the databse but in the form of BIN file which size is just 7 Bytes or 14 bytes and in the db it looks like [BLOB-14B] and [BLOB-7B]. But when i checked by directly uploading it on the database it worked pretty fine. What is the cause of the issue here
Here is the code of the form to get users image
<div class="form-group">
<label class="col-md-4 control-label">Upload image</label>
<div class="col-md-6">
<input type="file" class="form-control" name="image" id="image">
</div>
</div>
I am not including the whole form code here and have included only the code that gets image file.
Here is the controller function code
public function prof_details(Request $request)
{
$post = $request->all();
$val=\Validator::make($request->all(),
[
'firstname' => 'required',
'lastname' => 'required',
'username' => 'required',
'phone'=> 'required',
'nationality' => 'required',
'dobmonth' => 'required',
'dobyear' => 'required',
'dobday' => 'required',
'image' => 'required',
]
);
if ($val ->fails())
{
return redirect()->back()->withErrors($val->errors());
}
else
{
$data = array(
'firstname' => $post['firstname'] ,
'lastname' => $post['lastname'],
'username' => $post['username'],
'phone' => $post['phone'],
'nationality' => $post['nationality'],
'dobmonth' => $post['dobmonth'],
'dobyear' => $post['dobyear'],
'dobday' => $post['dobday'],
'image' =>$post['image'],
);
$updatedata = DB::table('users')->where('name',\Auth::user()->name)
->update($data);
if ($updatedata>0) {
return redirect('home');
}
else
{
return "something";
}
}
}
<input type="file" class="form-control" name="image" id="image">
Files are not stored in the $_POST variable but instead are stored in a temp file. You can obtain data on this file from the $_FILES variable 1 [2].
So, your uploaded file information would be in $_POST['image']. In order to obtain the actual image you would need to read the temp file that is stored in $_POST['image']['tmp_name'].

Use HTML5 input[type=file] to upload by different mobile in php, finally type is different

There is something confusing me. When I use input[type=file] to upload images in different mobile, I get different reponse in the server.
Here is the different response:
My question is that why i am uploading the image, but I do not get the same response in the server.
<form action="#" method="post" class='c-image-change-form' enctype="multipart/form-data">
<!-- <div class="oh jiaBtn active"> -->
<div class="oh jiaBtn">
<div class="oh pa">
<p id="id_img_list">
<a href="javascript:;" class="last" id="id_last_img_wrap">
<img src="http://cache.hinabian.com/mobile/images/jia3.png" alt="添加照片" />
<input name="upfile" type="file" class="file pa" id='id_upfile' accept="image/*" />
</a>
</p>
</div>
</div>
<div class="tc imgNum"><span class="color999">最多添加<em>9</em>张照片</span></div>
</form>
array (
'upfile' =>
array (
'name' => '16460',
'type' => 'application/octet-stream',
'tmp_name' => '/tmp/phpErjuTZ',
'error' => 0,
'size' => 1627225,
),
)
array ( 'upfile' => array (
'name' => 'IMG_20151030_124751.jpg',
'type' => 'image/jpeg',
'tmp_name' => '/tmp/phpOAHfmc',
'error' => 0,
'size' => 2090488, ), )
// Just use php's function imagecreatefromstring to create a picture, them imagepng ,imagejpg , imagejpeg to save a picture , then use it.
private function _imageCreateFromString($data)
{
$res = imagecreatefromstring($data);
if($res !== false)
{
//header('Content-Type: image/png');
imagepng($data);
imagedestroy($res);
}
}

Validation doesn't work for image upload in laravel 5

I have problem when validating inputs. All input fields pass the validation process except image fields.
This is my file upload code in html:
<div class="control-group">
<label class="control-label" for="fileInput"> Cover picture: </label>
<div class="controls">
{!! Form::file('cover') !!}
</div>
</div>
And how I get data from view in controller:
$datas = array(
'name' => Input::get('name'),
'color' => Input::get('color'),
'size' => Input::get('size'),
'cover' => array('cover' => Input::file('cover'))
);
And this is rules:
$rules = array(
'name' => 'required',
'color' => 'required',
'size' => 'required',
'cover' => 'required|mimes:jpeg,jpg,png|max:10000'
);
And Validation facades`s make method:
$validator = Validator::make($datas, $rules);
As I mentioned earlier, all validation rules passed for input, but for image it gives me an error:
The cover must be a file of type: jpeg, jpg, png.
Now, how can I fix it?
I think you should approach this a little differently...
If you instead just create your function like so..
// The Illumniate/Http/Request version of Request in laravel
public function yourFunction(Request $request){
....
$rules = ...;
$validator = Validator::make($request->all(), $rules);
}
The expected format of the Validator is handled automatically because it returns it. And when it runs through you can handle everything the same you already have.
Since this is accepted. The way to actually fix it with the code above is to just remove the multi-dimensional array and just use Input::file('cover') as it returns an array on its own.

Categories