I want to know how I can upload an image and save its name in a database when using Codeigniter.
I am using a simple form tag for this, like:
<form action="./myaccount/index/" method="post" enctype="multipart/form-data">
<div>
<label for="pic">picture</label>
<input type="file" id="pic" name="pic" />
</div>
<input id="register-btn" name="register" type="submit" value="ok" class="input-text custom-btn">
</form>
Here's my controller:
public function index() {
$user = new User($_SESSION['user_id']);
if($this->input->post()){
$user->pic = $this->input->post('pic');
if($this->input->post('password') == $this->input->post('confirm')){
$user->password=md5(sha1(sha1($this->input->post('password'))));
$user->save();
$this->data['success'] = "done";
}else{
$this->errors[] = "error";
}
}
$this->data['user'] = $user;
$this->data['errors'] = $this->errors;
$this->template->set_layout('myaccount');
$this->template->build('profile',$this->data);
}
I checked the manual but I can't understand what they are doing.
Im' trying to make a controler function for this that will insert all the values in the database and also upload the image file.
Related
Here on the update page load the image is displayed on the web page .
On update button click how to pass the image data(IFormFile) form view to controller.
If you want to pass IFormFile from view to controller,you can use a input which type is file,view cannot pass a <img/> to controller.Here is a demo:
View:
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="submit"/>
</form>
Controller:
[HttpPost]
public IActionResult Main(IFormFile image)
{
return View();
}
result:
Or you can pass a path to controller,and controller get the file with a path.
Image:
View:
<form method="post" enctype="multipart/form-data">
<input name="image" value="1.jpg" hidden/>
<img src="~/images/1.jpg" />
<input type="submit" value="submit" />
</form>
Controller:
[HttpPost]
public IActionResult Main(string image)
{
string path = "./wwwroot/images/" + image;
IFormFile File;
using (var stream = System.IO.File.OpenRead(path))
{
File = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name));
}
return View();
}
result:
i want build an Profile Picture Avatar Upload and display it in the Profile for every user.
Buts dont work with my method.
My Avatar Upload code:
<div class="form-group">
<div class="form-group">
<label for="exampleInputFile"><img src="/img/photos.png" height="80" width="80"> Upload Avatar:</label>
<input type="file" id="exampleInputFile" name="profileimage"></font></br>
</div>
</div>
Code where everyone see it in Profile:
<div class="pull-left margin-left-25">
#if($user->profileimage == false)
<img src="/img/icon.png" height="80" width="80">
#endif
#if($user->profileimage == true)
<img src="{{$user->profileimage}}" height="80" width="80">
#endif
ProfileController image content (Dont work for me):
if ($request->hasFile('image')) {
$file = $request->file('profileimage');
$size = $request->file('profileimage')->getSize();
if ($size > 500000) {
session()->flash('errormessage','Image is too large');
return redirect()->back()->withInput();
}
if (substr($file->getMimeType(), 0, 5) !== 'profileimage') {
session()->flash('errormessage','File is not an image');
return redirect()->back()->withInput();
}
if ($file->isValid()) {
$path = $request->profileimage->store('uploads','public');
} else {
session()->flash('errormessage','Image is not valid');
return redirect()->back()->withInput();
}
}
if ($request->image !== null) {
$product->image = $path;
}
What i have done wrong?
Thanks!
Why don't use Validator class?It will be so much easier than what you have coded. As the following,
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:500000',
]);
Add the above code inside the method in which you store the file and do your things.
It will do the validation for you, then continue whatever you want to do with the file. For more options please check the link provided.
Also, in your HTML code. You need to have a form in first place, action and its method, so your code should be:
<div class="form-group">
<div class="form-group">
<form action="{{ route('profile'}}" method="post">
<label for="exampleInputFile"><img src="/img/photos.png" height="80" width="80"> Upload Avatar:</label>
<input type="file" id="exampleInputFile" name="profileimage"></font></br>
</form>
</div>
</div>
And in your web.php, you should have the following line:
Route::get('/URL', 'ProfileController#MethodName')->name('profile');
Maybe it's because I'm tired, but I can't seem to get a simple upload working for one of my models.
On the show details page of my customers (who are NOT users) model, I have a simple form where a user can upload the logo of the customer.
The form:
<form enctype="multipart/form-data" action="/customers/i/{{$customer->url_string}}" method="POST">
<input type="file" name="logoUpload">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="submit" class="pull-right btn btn-sm btn-primary" value="Upload">
</form>
The Controller:
public function logoUpload(Request $request){
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
$customer->car_logo = $path;
$customer->save();
return back();
}
}
I know the issue is that I haven't defined $customer in the controller since the file does actually store itself in the correct folder after I click submit, but it does not hit the database at all.
Update
The current customer details url:
http://localhost:8000/customers/i/dsdado9a98w78721
The web definition for the post route:
Route::post('/customers/i/{customer}', 'CustomerController#logoUpload');
You have to create a hidden field in your form that contains the customer id and then use it in your controller to update it with the new file path, here is an example:
View
<form enctype="multipart/form-data" action="/customers/i/{{$customer->url_string}}" method="POST">
<input type="file" name="logoUpload">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<!-- customer_id field -->
<input type="hidden" name="customer_id" value="{{$customer->id}}">
<input type="submit" class="pull-right btn btn-sm btn-primary" value="Upload">
</form>
Controller
public function logoUpload(Request $request){
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
// get customer
$customer = Customer::find($request->customer_id);
$customer->car_logo = $path;
$customer->save();
return back();
}
}
You have some options, here is a simple one, with only adjusting that controller method:
public function logoUpload(Request $request, $customer)
{
$customer = Customer::where('url_string', $customer)->firstOrFail();
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
$customer->car_logo = $path;
$customer->save();
return back();
}
...
}
We have added a parameter to the method signature to accept the route parameter. We then find the model via url_string matching that parameter.
You also could setup route model binding as well to do the resolving of that model based on the route parameter for you.
I have a view in Codeigniter that is a form written in HTML directly.
<form action="http://localhost/index.php/cindice/mostrar" mehtod="post">
<label for="usuario" id="usr">Usuario</label>
<input type="text" name="usuario" /><br /><br />
<label for="contrasenya" id="ctr">ContraseƱa</label>
<input type="password" name="contrasenya" id="ctr" />
<label for="acceder"></label><br /><br />
<input type="submit" name="acceder" id="bacceder" value="Entrar" />
</form>
The form has two fields: usuario (user) and contraseƱa (password).
And it is the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cindice extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index()
{
$this->load->view('indice');
}
public function mostrar()
{
$mostrar=$this->input->post('usuario');
print_r($_POST);
echo "<br />";
}
}
?>
When I load the page localhost/index/cindice and I write a username and a password. But the result of print_r($_POST) command is array(), what it means that any value was saved in the form.
How can I fix it?
I think it is empty because you have spelled the the method attribute wrong in your opening form tag. You have put
<form action="http://localhost/index.php/cindice/mostrar" mehtod="post">
When it should be
<form action="http://localhost/index.php/cindice/mostrar" method="post">
Be mindful if you have CSRF switched on in your config - if it is then you need to use the codeigniter form helper and form_open() so that the hidden security value is added.
I'm stuck writing a simple form...I feel dumb.
Here's my controller:
function welcome_message(){
//Update welcome message
$id = $this->session->userdata('id');
$profile['welcome_message'] = $this->input->post('welcome_message');
$this->db->update('be_user_profiles',$profile, array('user_id' => $id));
}
And the html:
<?php print form_open('home/welcome_message')?>
<input type="checkbox" value="0" checked="false">Don't show me this again</input>
<p>
<input class="button submit" type="submit" class="close-box" value="Close" />
</p>
<?php print form_close()?>
Edit
I simply need it to submit to a private function and return to the home page (page submitted from).
You have to name your input...?
<input type="checkbox" value="0" name="welcome_message" checked="false">
Don't show me this again
</input>
EDIT: You can't submit to a private function via the URL (in a default CI installation, anyway).
Do it like this:
function welcome_message()
{
if(isset($_POST['welcome_message']))
{
$this->_my_private_function();
}
}
private function _my_private_function()
{
// do your thing with the $_POST data
redirect('your/uri', 'location');
}
But you really don't have to redirect if your returning to the same page (controller method) that called the private function in the first place. Would be a waste.