When I update the database, it uploads a single image. How do I upload multiple?
$id = $this->request->getPost('id');
$model = new UrunModel();
$file = $this->request->getFile('resim');
$resim_eski = $model->find($id);
if($file->isValid() && !$file->hasMoved()){
$eski_resim = $resim_eski['resim'];
if(file_exists("dosyalar/uploads".$eski_resim)){
unlink("dosyalar/uploads".$eski_resim);
}
$imagename = $file->getRandomName();
$file->move("dosyalar/uploads", $imagename);
}else{
$imagename = $resim_eski['resim'];
}
if ($this->request->getFileMultiple('images')) {
foreach($this->request->getFileMultiple('images') as $res)
{
$res->move(WRITEPATH . 'dosyalar/uploads');
$data=[
'baslik' => $this->request->getPost('baslik'),
'slug' => mb_url_title($this->request->getPost('baslik'), '-', TRUE),
'kisa_aciklama' => $this->request->getPost('kisa_aciklama'),
'kategori' => $this->request->getPost('kategori'),
'query_kategori' => $this->request->getPost('query_kategori'),
'aciklama' => $this->request->getPost('aciklama'),
'fiyat' => $this->request->getPost('fiyat'),
'indirimli_fiyat' => $this->request->getPost('indirimli_fiyat'),
'resim' => $imagename,
'resimler' => $res->getClientName(),
'type' => $res->getClientMimeType()
];
$model -> update($id,$data);
}
}
return redirect()->to(base_url('yonetim/urunler'));
}
Controller code above, I've been struggling for 2 days, I couldn't manage it somehow.
When I run the code, it just adds 1 image to each product. I want to add more than one image to 1 product for the gallery part. Any suggestions for this code or a different solution?
function add()
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table',$data);
}
CI4 Controller:
if($this->request->getFileMultiple('image_files')) {
$files = $this->request->getFileMultiple('image_files');
foreach ($files as $file) {
if ($file->isValid() && ! $file->hasMoved())
{
$newNames = $file->getRandomName();
$imageFiles = array(
'filename' => $newNames
);
$modelName->insert($imageFiles );
$file->move('uploads/', $newNames);
}
}
}
HTML
<input type="file" name="image_files[]">
This is the shortest way to do that
Related
i can't upload file more than 2 MB in codeigniter 4. How to increase the limit size in codeingiter 4?
public function store()
{
helper('text');
$data = $this->request->getPost();
if($data['type'] === 'structure and written expression'){
$file = $this->request->getFile('story');
$path = WRITEPATH.'uploads';
$filename = $file->getRandomName();
$file->move($path, $filename);
$data = [
'type' => $data['type'],
'text_question' => $filename
];
}
$story = new StoryModel;
$id = $story->insert($data);
if($story->errors())
{
return $this->fail($story->errors());
}
if($id === false)
{
return $this->failServerError("Server Error");
}
$data=null;
return $this->respondCreated(['status' => 'created success', 'id'=>$id]);
}
this is my create function in controller
I agree what in link with Marged shared, and you can add more code to compress image with:
$config['quality']='50%';
In my property section I have two property types:
Freemium
Premium
I want to restrict users to upload only 5 images for Freemium property type while for Premium properties a user can upload infinitive number images and videos.
Must needed some suggestions.
Here is my image upload part :
public function postProperty(PropertyRequest $request)
{
$user = User::where('id', $request->user->user_id)->first();
if(!empty($user))
{
$data['user_id'] = $user->id;
$data['type'] = $request->type;
$data['category'] = $request->category;
$data['area'] = $request->area;
$data['price'] = $request->price;
$data['description'] = $request->description;
//dd($data);
$property = Property::create($data);
//$property['flag'] = false; // if (flag = false, property = freemium) else (flag = true, property = premium ))
$urls = new PropertyImage();
if ($request->hasFile('url'))
{
$files = $request->file('url');
foreach($files as $file)
{
$mime = $file->getMimeType();
//$property['flag'] = $property->account == 1 ? false : true;
if($mime == 'image/jpeg')
{
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/images/';
$file->move($destinationPath, $fileName);
$urls->url = '/public/images/' . $fileName;
$url_data = [
'property_id' => $property->id,
'url_type' => 1,
'url' => $urls->url,
];
$urls->create($url_data);
}
elseif($mime == 'video/mp4')
{
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/videos/';
$file->move($destinationPath, $fileName);
$urls->url = '/public/videos/' . $fileName;
$url_data = [
'property_id' => $property->id,
'url_type' => 2,
'url' => $urls->url,
];
$urls->create($url_data);
}
}
}
return Utility::renderJson(trans('api.success'), true, $property, $urls );
}
}
You can use laravel validation to restrict user to some number of files as shown below
//If user is Freemium then restrict him
if (!$property['flag']) {
$messages = [
"url.max" => "files can't be more than 3."
];
$this->validate($request, [
'url' => 'max:3',
],$messages);
}
I'm trying to upload multiple image in codeigniter. For a particular product I want to add the uploaded images to another table calles"image".... while using "lastid" so that I get pid(product id from table product_multi) in images multiples rows are inserted in the product_multi table... the number rows is according to the number of images I upload. Someone help me to fix this.. If I'm not using lastid variable passing it works perfectly/... but I want pid in images tables :(
This is how im getting datable
This is my model
<?php
class ProductmModel extends CI_Model
{
var $PRODUCTNAME='';
var $DESCRIPTION='';
var $CATEGORY='';
var $SUBCAT='';
var $IMAGE='';
public function addproductm()
{
$this->load->database();
$data = array(
"p_name" => $this->PRODUCTNAME,
"p_des" => $this->DESCRIPTION,
"cat" => $this->CATEGORY,
"subcat" => $this->SUBCAT
);
$this->db->insert('product_multi', $data);
$lastid=$this->db->insert_id();
echo "$lastid";
return $lastid;
}
public function addimage()
{
$last=$this->addproductm();
$this->load->database();
$data = array(
"pid" =>$last,
"images" => $this->IMAGE
);
$this->db->insert('image', $data);
}
}
controller code::
public function upload()
{
//image upload
$config['upload_path'] = './images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload',$config);
$this->upload->initialize($config);
$fileInfos = array();
$errors = array();
//uploading
if (! empty($_FILES['images']['name']))
{
$photosCount = count($_FILES['images']['name']);
for ($i = 0; $i < $photosCount; $i ++)
{
$_FILES['image']['name'] = $_FILES['images']['name'][$i];
$_FILES['image']['type'] = $_FILES['images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['images']['error'][$i];
$_FILES['image']['size'] = $_FILES['images']['size'][$i];
if ($this->upload->do_upload('image'))
{
array_push($fileInfos, array(
'fileInfo' => $this->upload->data()
));
$filename =$_FILES['image']['name'] ;
//$filename =$_FILES["name"].$_FILES["type"];
// $data['fileInfos'] = $fileInfo;
$this->load->model("ProductmModel");
$this->ProductmModel->IMAGE = $filename;
}
else
{
array_push($errors, array(
'error' => $this->upload->display_errors()
));
}
}
}
$pname = $this->input->post("name");
$pdes = $this->input->post("pdes");
$caty = $this->input->post("category");
$subcat = $this->input->post("subcat");
$this->ProductmModel->PRODUCTNAME = $pname;
$this->ProductmModel->DESCRIPTION = $pdes;
$this->ProductmModel->CATEGORY = $caty;
$this->ProductmModel->SUBCAT = $subcat;
$this->ProductmModel->addproductm();
}
This is the code after editing as u said...making both insertion in single function
exampleee:
public function upload(){
//image upload
$config['upload_path'] = './images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload',$config);
$this->upload->initialize($config);
$fileInfos = array();
$errors = array();
//uploading
if (! empty($_FILES['images']['name']))
{
$photosCount = count($_FILES['images']['name']);
for ($i = 0; $i < $photosCount; $i ++)
{
$_FILES['images']['name'] = $_FILES['images']['name'][$i];
$_FILES['images']['type'] = $_FILES['images']['type'][$i];
$_FILES['images']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
$_FILES['images']['error'] = $_FILES['images']['error'][$i];
$_FILES['images']['size'] = $_FILES['images']['size'][$i];
if ($this->upload->do_upload('images'))
{
$data = $this->upload->data();
array_push($fileInfos, $data['file_name']);
}
else{
array_push($errors, array(
'error' => $this->upload->display_errors()
));
}
}
}
$product_array = array(
"p_name" => $this->input->post("name"),
"p_des" => $this->input->post("pdes"),
"cat" => $this->input->post("category"),
"subcat" => $this->input->post("subcat")
);
$this->ProductmModel->addproductm($product_array, $fileInfos);
}
Model
public function addproductm($product_array, $fileInfos){
$this->load->database();
$this->db->insert('product_multi', $product_array);
$lastid = $this->db->insert_id();
foreach($fileInfos as $file){
$image_data = array(
"pid" => $lastid,
"images" => $file
);
$this->db->insert('image', $image_data);
}
}
My codes multiple image upload and update mysql db but one problem if id=1 It's working multiple image uploading and update.else It's not working and white page.
tables 2
musteri_soru and musteri_cevap
is updating musteri_cevap in colon resim
controller code:
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
if($_FILES){
$dizin= "../upload/form_cevap/";
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++){
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
Models code :
function duzenle($no,$data)
{
$this->db->update($this->tablo,$data, array('no' => $no));
}
function cevapDuzenle($n,$dat)
{
$data = array('resim' => $dat);
$this->db->update($this->ctablo,$data, array('soru_no' => $n));
}
My Tables
enter link description here
To be honest, I'm not quite sure how your upload was working as the $_FILES array shouldn't be nesting the uploads in the way you've shown above.
I'm not saying this will definitely work but it should do:
function duzenle($no)
{
//I would possible look at using the Form_validation Library here
if (empty($_POST)) {
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no, $arr1);
if (!empty($_FILES)) {
$dizin = "../upload/form_cevap/";
foreach ($_FILES as $name => $file) {
//If there is an error there isn't any reason to try and upload this file
if ($file['error'] !== 0) {
continue;
}
$name = $file['name'];
$isim = md5(uniqid(rand()));
move_uploaded_file($file['tmp_name'], "./$dizin/$isim$name");
$arr['resim'] = $dizin . $isim . $name;
//Not sure what's going on here so I haven't changed it
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach ($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else {
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik' => $veri->baslik,
'veri' => $veri,
'cevap' => $veri2
);
$this->bc->addCrumb($veri->baslik, 'form_duzenle/duzenle/' . $veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle', $data);
}
}
Hope this helps!
Check your for loop,
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++)
for loop condition should be $i < $dosya_sayi as array index always starts from 0.
So correct for loop is
for($i=0;$i<$dosya_sayi;$i++)
I solved the problem.Duzenle codes on change the bottom code.
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
$cevaplar = $this->form_duzenle_model->cevapListe($no)->result_array();
if($_FILES){
$dizin= "../upload/form_cevap/";
foreach($cevaplar AS $cevap){
$i = $cevap['no'];
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
$this->form_duzenle_model->cevapDuzenle($i,$arr['resim']);
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
i ma trying to upload multiple images from HTML FORM but on submit only last image uploaded please any one who can figure out this problem
here is my controller
if($_FILES['image']['name'] != "")
{
$data['image'] = $this->MUtils->doUpload('image',270,65,false);
}
if($_FILES['adv_image1']['name']!= "")
{
$data['adv_image1'] = $this->MUtils->doUpload('adv_image1',340,130,false);
}
if($_FILES['adv_image2']['name']!= "")
{
$data['adv_image2'] = $this->MUtils->doUpload('adv_image2',860,100,false);
}
Model is
if($data['image']!="" ){
$arr=array('image' => $data['image']);
}
if($data['adv_image1']!=""){
$arr=array('adv_image1' => $data['adv_image1']);
}
if($data['adv_image2']!=""){
$arr=array('adv_image2' => $data['adv_image2']);
}
if($data['adv_image3']!=""){
$arr['adv_image3'] = $data['adv_image3'];
}
$this->db->where('id',$data['listid']);
$this->db->update('list', $arr);
return 1;
doUpload Functio is here
//Upload file and return url
function doUpload($field, $width, $height, $resize=false)
{
//Configure upload.
$this->upload->initialize(array(
"upload_path" => "../uploads/",
"allowed_types" => "gif|jpg|png",
));
//Perform upload.
if($this->upload->do_upload($field)){
$fileData = $this->upload->data();
if ($resize == true)
{
$width = $fileData['image_width'];
$height = $fileData['image_height'];
}
$img_cfg_thumb['image_library'] = 'gd2';
$img_cfg_thumb['source_image'] = "../uploads/" . $fileData['raw_name'] . $fileData['file_ext'];
$img_cfg_thumb['maintain_ratio'] = FALSE;
$img_cfg_thumb['new_image'] = "../uploads/" . $fileData['raw_name'] . $fileData['file_ext'];
$img_cfg_thumb['width'] = $width;
$img_cfg_thumb['height'] = $height;
$img_cfg_thumb['quality'] = 90;
$this->load->library('image_lib');
$this->image_lib->initialize($img_cfg_thumb);
$this->image_lib->resize();
return $fileData['raw_name'] . $fileData['file_ext'];
}
else
{
return "";
}
}
Note this is working, but from three pics just last one is uploaded on submit
In your model change following lines:
if($data['image']!="" ){
$arr=array('image' => $data['image']);
}
if($data['adv_image1']!=""){
$arr=array('adv_image1' => $data['adv_image1']);
}
if($data['adv_image2']!=""){
$arr=array('adv_image2' => $data['adv_image2']);
}
if($data['adv_image3']!=""){
$arr=array('adv_image3' => $data['adv_image3']);
}
To these lines:
if($data['image']!="" ){
$arr['image'] = $data['image'];
}
if($data['adv_image1']!=""){
$arr['adv_image1'] = $data['adv_image1'];
}
if($data['adv_image2']!=""){
$arr['adv_image2'] = $data['adv_image2'];
}
if($data['adv_image3']!=""){
$arr['adv_image3'] = $data['adv_image3'];
}
You need to clear your config and lib each time.
Try below code at starting of the function:
unset($config)
$this->upload->clear();
Hope this helps