I know this question has been asked millions of times, but all of the questions are a little bit too difficult for beginners.
So what I'm looking for is how to create a simple button that uploads an image and get its full_path and save it in a hidden input of the form, so when i click submit, the form will insert the path with the other inputs, and so the image would have been uploaded to a directory.
It's a simple project, a basic blog page, where I need the following the inputs to be saved:
1. Image
2. Title
3. Body
The only thing i couldn't accomplish is the image part.
So here's the view code:
<h1>Add New Post</h1>
<br />
<?=form_open('admin/add_post');?>
<p>
<input type="text" name="title" />
</p>
<input hidden="hidden" name="date" value="<?php echo date('d-m-y');?>"/>
<p>
<textarea id="textarea" name="body" rows="10"></textarea>
</p>
<p>
<input type="submit" value="Submit Post" />
</p>
</form>
and here's the controller when you click Submit:
// Adds new posts to the database table
function add_post()
{
$this->form_validation->set_rules('title', 'Title', 'required|min_length[2]');
$this->form_validation->set_rules('body', 'Body', 'required|min_length[2]');
if ($this->form_validation->run() == TRUE) {
// INSERTING GOES HERE..
$this->db->insert('entries', $_POST);
redirect('admin/posts');
}
else {
redirect('admin/add');
}
}
So please I need someone to tell me how to write the upload function to upload the image on the same page and on the same form, and save its path to the database.
I can make it save the path, but i wanna get the path first and add it to the same form in a hidden input, EX:
Please I really need your help, and if you have any idea on how to help me, please post your answer.
Thanks in advance.
It's very simple to achieve this with CodeIgniter.
I'll use the Version 3.1.0 reference:
View:
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
Controller:
public function do_upload() {
$fileData = array();
// File upload script
$this->upload->initialize(array(
'upload_path' => './uploads/',
'overwrite' => false,
'max_filename' => 300,
'encrypt_name' => true,
'remove_spaces' => true,
'allowed_types' => 'gif|jpg|png',
'max_size' => 100,
'xss_clean' => true,
));
$this->form_validation->set_rules('title', 'Title', 'required|min_length[2]');
$this->form_validation->set_rules('body', 'Body', 'required|min_length[2]');
if ($this->form_validation->run() == TRUE) {
if ($this->upload->do_upload('userfile')) {
$data = $this->upload->data(); // Get the file data
$fileData[] = $data; // It's an array with many data
// Interate throught the data to work with them
foreach ($fileData as $file) {
$file_data = $file;
}
var_dump($file_data);
$this->db->insert('entries', array(
// So you can work with the values, like:
'title' => $this->input->post('title', true), // TRUE is XSS protection
'body' => $this->input->post('body', true),
'file_name' => $file_data['file_name'],
'file_ext' => $file_data['file_ext'],
));
$this->session->set_flashdata('success', 'Form submitted successfully');
redirect('admin/add');
} else {
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/add');
}
} else {
$this->session->set_flashdata('error', validation_errors());
redirect('admin/add');
}
}
You can use var_dump to see available data to work, or see the documentation (on the bottom)
https://www.codeigniter.com/userguide3/libraries/file_uploading.html
Related
I am trying to work with uploading multiple images on my project but it is not saving into the database
public function store(Request $request)
{
//validate
$this->validate($request, [
'subject'=>'required|min:10',
'tags' => 'required',
'body' => 'required|min:20',
'filename' => 'sometimes',
'filename.*' => 'file|image|mimes:jpeg,png,jpg,gif,svg|max:5000'
]);
//store
$news=auth()->user()->news()->create($request->all());
$news->tags()->attach($request->tags);
$this->storeImage($news);
//redirect
return redirect()->route('news.index');
}
private function storeImage($news)
{
if (request()->has('image')) {
foreach (request()->file('filename') as $file) {
$news->update([
'filename' => request()->filename->store('uploads', 'public'),
]);
}
}
}
Upload HTML:
<div class="form-group">
<label for="image"><b>Select Image To Add</b></label>
<input type="file" name="filename[]">
</div>
How can I make the file save into the database as it is not saving to the database at all? Could anyone help me to solve this problem please?
It is not a good idea to save images in the database. Keep the files in your public folder on the server and save the file paths in the database only.
update your form like this
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/store-image">
add multiple to the input
<div class="form-group">
<label for="image"><b>Select Image To Add</b></label>
<input type="file" name="filename[]" multiple >
</div>
update your storeImageFunction Like this
public function storeImage(request $request) {
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
}
Now, you have got all the image paths in the images array.
I am try upload the file with Postman,but get the wrong message:You did not select a file to upload. I do not know what is the reason, but also trying to find ways.
Look at the gif of Postman:
Look at the php code:
public function upload_post()
{
$this->load->helper(array('form', 'url'));
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload',$config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
$this->set_response($data, REST_Controller::HTTP_CREATED);
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->response($error, REST_Controller::HTTP_BAD_REQUEST);
}
}
Look at the html:
<?php echo $error;?>
<?php echo form_open_multipart('api/example/upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
Upload file with the browser is OK!
Two code is OK!Browser upload no problem!But can not upload with Postman!
Has been solved, the original is not added $this->upload->do_upload('file') and key file postman.
could you put your form code ? i think you forgot to add enctype='multipart/form-data'
Hello im newbie in laravel so i really need some help. I want to create a code where only the image that can upload other files can not, I have tried to use the code input file but when I try to upload the zip file file it still uploaded so I really need help
This is my table code
<div class="col-sm-5">
{!! Form::label('photo', 'Photo:') !!}
<input type='file' name='photo' class='form-control' accept = 'image/jpeg , image/jpg, image/gif, image/png'>
And this is my Controller
public function store(CreateBannerRequest $request)
{
$input = $request->all();
//get original file name
if($request->photo == NULL)
{
Flash::error('Image must be filled');
return back();
}
$filename = Input::file('photo')->getClientOriginalName();
$input['photo'] = $filename;
$banner = $this->BannerRepository->create($input);
//upload file
Input::file('photo')->move($this->path, $filename);
Flash::success('Banner saved successfully.');
if (empty($banner)) {
Flash::error('No image available');
return redirect(route('banner.index'));
}
return redirect(route('banner.index'));
}
You have code at front end like this:
View
<form action="{{URL::to('upload/photo')}}" class="form-horizontal" method="POST" role="form" enctype="multipart/form-data">
<input type="file" name="photo">
<button class="btn btn-default pull-right" type="submit">Create</button>
</form>
Route
Route::post('upload/photo','TestController#uploadPhoto');
TestController
public function uploadPhoto(Request $request)
{
$this->validate($request, [
'photo' => 'mimes:jpeg,png,bmp,tiff |max:4096',
],
$messages = [
'required' => 'The :attribute field is required.',
'mimes' => 'Only jpeg, png, bmp,tiff are allowed.'
]
);
// Now save your file to the storage and file details at database.
}
I hope, you undestand.
you can do it with validation throuhg mimes:jpeg and the other types such as png etc. lookup laravel validation on the documentation page
I have some problem in image uploading with php codeigniter.
this is my controller
public function FunctionName()
{
$profile_pic = $this->input->post('profile_pic');
echo $profile_pic;
}
It is a simple function and I just want to see the name of the file (image) which I select.
this is my view
<form class="" method="post" action="<?=base_url();?>Controller/FunctionName" enctype="multipart/form-data">
<input type="file" name="profile_pic">
<input type="submit" name="submit">
</form>
When I run this script. It shows me a blank page. I cannot get/display the name of the file which I selected. Note that I have auto-loaded the helper. E.g.
$autoload['helper'] = array('url', 'file', 'date', 'form');
$file=$_FILES['file_name']['name'];
$config = array('file_name'=>$file,
'upload_path' => "./folder/",
'allowed_types' => "jpg|jpeg|png",
'remove_spaces' => FALSE,
'overwrite' => TRUE
);
$this->load->library('upload', $config);
$this->upload->do_upload('file_name');
I have form with a file input in my CodeIgniter website. When I fill in the form and click the submit button it's working fine. However, when I refresh the browser the same form data is uploaded again. How can I prevent this ?
input form
<form name="image_upload" action="<?= base_url() ?>admin/image_move_upload" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<ul>
<li class="ui-field"><label for="filename">File Name :</label></li>
<li class="ui-input"><input type="text" name="filename" placeholder=""></li>
<li class="ui-field"><label for="file">Image( *only .jpg) :</label></li>
<li class="ui-input"><input type="file" name="imagefile" value="" placeholder="" required=""></li>
<li><input type="submit" name="Upload" class="ui-submit"></li>
</ul>
</form>
controller section
function image_move_upload() {
$data['errors'] = NULL;
$data['success'] = NULL;
if (isset( $_POST['Upload'] )) {
$config_arr = array(
'upload_path' => './uploads/slider/',
'allowed_types' => 'jpg',
'max_size' => '2048',
'max_width' => '1024',
'max_height' => '768',
'encrypt_name' => true,
'file_name' => 'sanji.jpg',
);
$this->load->library('upload', $config_arr);
if (!$this->upload->do_upload('imagefile')) {
$data['errors'] = $this->upload->display_errors(); // this isn't working
} else {
$data['qs'] = $this->upload->data();
$data['success'] = "File Uploaded Successfully";
}
}
$data['main_content'] = 'admin/upload';
$this->load->view('admin_layout', $data);
}
Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get
redirect to same controller with refresh. Use following code.
redirect('admin/image_move_upload', 'refresh');
Use Redirect Function rather than calling a function of same class.
So, Use redirect('admin/image_move_upload', 'refresh');