I have implemented dropzone js on my laravel project but af facing one issue on saving the images on the database
,/uploads/products/27/607f0fc0942b0_1618939840_fc3cde370d846c4d14b0200a29e9206f.png,/uploads/products/27/607f0fc0945e8_1618939840_copy-space-with-opened-quran_23-2148214357.jpg,/uploads/products/27/607f0fc09474d_1618939840_1 (1).jpg
the issue is the images start with a comma which is wrong and it must be after the image for example
image1.png,image2.png
Here is my Controller
$product_images = json_decode($request->product_images[0],true);
$images = [];
$path = "";
$productsPath = 'uploads/products/';
$productPath = 'uploads/products/'.$request->product_id;
if(!file_exists($productsPath)){
mkdir($productsPath);
}
if (!file_exists($productPath)) {
mkdir($productPath, 0777,true);
}
foreach($product_images as $img){
$file = $img['name'];
// $extension = $img->guessExtension();
$filename = uniqid() .'_'. time() .'_'. $file;
$img = explode(',',$img['file'])[1];
$img = str_replace('', '+', $img);
$data = base64_decode($img);
$file = $productPath .'/'. $filename;
$success = file_put_contents($file, $data);
// dd($file);
$images[] = '/'. $file;
}
// Update Product Information On "products" table
$product = Product::where('id', $request->product_id)->first();
$product->created_by = auth()->user()->id;
$product->name = request('name_en');
$product->name_ar = request('name_ar');
$product->description = request('description_en'); // Must be moved to "product_information"
$product->description_ar = request('description_ar'); // Must be moved to "product_information"
$product->youtube = request('youtube'); // Must be moved to "product_information"
$product->youtube_ar = request('youtube_ar'); // Must be moved to "product_information"
$product->slug = slugify($request->name_en, 'Product', '', '');
// $product->image = request('name_en');
$product->brand_id = request('brand');
$product->status = request('status');
$data = explode(',' ,$product->image);
$data = array_merge($data,$images);
$remove_images = json_decode($request->removed_images, true);
$temp = [];
$i = 0;
foreach($data as $key => $imag){
$i = $i + 1;
if(!empty($remove_images) && in_array($imag, $remove_images)){
if (file_exists($productPath .'/'. $imag)) {
unlink($productPath .'/'. $imag);
}
}else{
if($i < 8)
$temp[] = $imag;
}
}
$product->image = implode($temp, ',');
// dd (explode(',' ,$product->image));
$product->save();
thank you
use implode like this
implode(',', $temp);
Related
I am currently working on an uploading site. Here is my function for saving image name to database and uploading it to server from a base64 data.
public function addImages($order_last_id, $cropped)
{
// this is for saving the base64 image to database
$order = $this->Order_model->get($order_last_id);
// if(!$data){
// return false;
// }
//$images = [];
$cropped_image = [];
$date = new DateTime();
$startdata = $date->format('YmdHis');
$newName = str_replace('/', '', $startdata);
$image_name = $newName;
$i = $this->db->insert_id();
foreach ($cropped['cropped_images'] as $keys => $output){
// $cropped_image[] = $output;
$res[] = ['cropped_images' => $image_name.$i.".jpg",
'order_id' => $order_last_id];
$i++;
}
// foreach ($data['name'] as $key => $image){
// $images[] = $image;
// }
// this is for uploading the base64 image to files
$date = new DateTime();
$startdata = $date->format('YmdHis');
$newName = str_replace('/', '', $startdata);
$image = [];
$image_name = $newName;
$i = $this->db->insert_id();
foreach ($cropped['cropped_images'] as $key => $value) {
$image[] = $value;
file_put_contents(
"uploads/orders/".$image_name.$i.".jpg",
base64_decode(
str_replace('[removed]', '', $value)
)
);
$i++;
}
return $this->db->insert_batch('orderimages', $res);
}
now, What i want to do is display the file_put_contents() progress to my view. how can i Achieve that?
any help would be appreciated.
PS: I can't find anyting about this question on the net so I hope someone can help me
I am trying to add multiple images one for the banner images other multiple images for the gallery images but when I try to add an image it gives me the error:
array to string conversation.
I want to add one image into the same table and other images into the different table so when I will show record into my view I can one banner image easily.
I will be very thankful if someone help me in this.
so here is the my view.
<div class="col-lg-12">
<label for="main image">Upload Main Image: </label><br>
<input type="file" name="image_file">
</div><br><br><br>
<div class="col-lg-12">
<label for="Image name">Upload Mutiple Images:</label><br>
<input type="file" required name="image_name[]" multiple/><br>
</div>
// Model
function addnews($data, $id ='')
{
$title = $this->input->post('title');
$address = $this->input->post('address');
$city = $this->input->post('city');
$zip = $this->input->post('zipcode');
$type = $this->input->post('propertytype');
$status = $this->input->post('status');
$price = $this->input->post('price');
$description = $this->input->post('Description');
$userfile = $this->input->post('[image_file]');
$bedrooms = $this->input->post('bedrooms');
$rooms = $this->input->post('rooms');
$bath = $this->input->post('bathroom');
$garages = $this->input->post('gerages');
$date = $this->input->post('date');
$amenities = implode(',',$this->input->post('check'));
$w = array (
'title' => $title,
'address' => $address,
'city' => $city,
'zip' => $zip,
'type' => $type,
'status' => $status,
'description' => $description,
'bedrooms' => $bedrooms,
'rooms' => $rooms,
'price' => $price,
'userfile' => $data,
'bath' => $bath,
'date' => $date,
'garages' => $garages,
'amenities' => $amenities
);
$this->db->insert_batch("property", $w);
$id = $this->db->insert_id();
foreach ($data as $row) { // here data is from parameter
$data1[] = array(
'property_id' => $id, //Insert Inserted id
'image_name' => $row['file_name'] // this line is changed
);
}
}
// My controller.
public function addlisting()
{
$this->load->library('upload');
$config['upload_path']='./uploads';
$config['allowed_types']='*';
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image_file')) {
$this->session->set_flashdata('msg',"Failed To Apply. Please Check All The Fields.");
redirect(site_url('Welcome/add_listing'));
} else {
$fd = $this->upload->data();
$fn = $fd['file_name'];
//$this->User_model->addnews($fn);
$image = array();
$ImageCount = count($_FILES['image_name']['name']);
for ($i = 0; $i < $ImageCount; $i++) {
$_FILES['file']['name'] = $_FILES['image_name']['name'][$i];
$_FILES['file']['type'] = $_FILES['image_name']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image_name']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['image_name']['error'][$i];
$_FILES['file']['size'] = $_FILES['image_name']['size'][$i];
// File upload configuration
$uploadPath = './uploads';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if ($this->upload->do_upload('file')) {
// Uploaded file data
$imageData = $this->upload->data();
$uploadImgData[$i]['file_name'] = $imageData['file_name'];
} else {
$this->session->set_flashdata('msg',"Error while uploading Data");
// $this->User_model->addnews($uploadImgData);
redirect(site_url('Welcome/add_listing'));
}
}
if (!empty($uploadImgData)) {
//Insert files data into the database
$this->User_model->addnews($uploadImgData);
$this->User_model->addnews($fn);
// $query = implode(",",$uploadImgData);
// $insert = $this->User_model->add($uploadImgData);
$this->session->set_flashdata('msg',"Property Uploaded successfully");
redirect('Welcome/add_listing');
}
}
try to change name or config array
public function add_model()
{
$this->before_login();
$data = array();
$data['mode'] = "ADD";
$db_name = 'para';
$table = 'models';
$sess = $this->session->userdata('admin');
$data['a_name'] = $sess['name'];
$data['record'] = $this->Paramodel->select('brand','brand_name,id');
if($this->input->post('submit'))
{
$this->Database->add_new_model($table,$db_name);
foreach($_POST as $key=>$value)
{
$$key=trim($value);
}
// Form Validation Run
if($this->form_validation->run('add_model'))
{
if(strlen($_FILES['model_display_picture']['name']) > 0)
{
$config['upload_path'] = './assets/Model/';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 2048;
$config['encrypt_name'] = TRUE;
// directry Path
$this->load->library('upload',$config);
$slug = $this->clean_url($model_name);
$this->upload->initialize($config);
if($this->upload->do_upload('model_display_picture'))
{
$result=$this->last_record('models')[0]['setord'];
// echo "<pre>";
// print_r($result);
// exit;
if($result == "" ){ $last_setord_no = 1; }else{ $last_setord_no = $result+1; }
$image_path = './assets/Model/'.$this->upload->data('file_name');
// INSERT DATA
$ins['brand_id'] = $brand_id;
$ins['model_type'] = $model_type;
$ins['model_name'] = $model_name;
$ins['model_description'] = $model_description;
$ins['model_display_image'] = $image_path;
$ins['status'] = $status;
$ins['slug'] = $slug;
$ins['setord'] = $last_setord_no;
$ins['meta_title'] = addslashes($meta_title);
$ins['meta_descryption'] = $meta_description;
$ins['meta_keywords'] = $meta_keywords;
$ins['u_create_date'] = date('Y-m-d H:i:s');
// INSERT QUERY
$insert = $this->Paramodel->insert('models',$ins);
$insert_id = $this->db->insert_id();
$this->_create_thumbs($this->upload->data('file_name'));
// INSERT SUCCESS CONDITION
if( $insert == 1 )
{
$count = count($_FILES['model_images']['name']);
if( $count > 0)
{
$this->Database->model_image('model_image');
for($i = 0 ; $i < $count ; $i++ )
{
$_FILES['single']['name'] = $_FILES['model_images']['name'][$i];
$_FILES['single']['type'] = $_FILES['model_images']['type'][$i];
$_FILES['single']['tmp_name'] = $_FILES['model_images']['tmp_name'][$i];
$_FILES['single']['size'] = $_FILES['model_images']['size'][$i];
$_FILES['single']['error'] = $_FILES['model_images']['error'][$i];
$config1['upload_path'] ='./assets/Model/';
$config1['allowed_types'] = 'jpg|jpeg|png';
$config1['max_size'] = 2048;
$config1['encrypt_name'] = TRUE;
// echo "<pre>";
// print_r($config1);
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
// echo "<pre>";
// print_r($_FILES['single']);
// echo "------------------";
if($this->upload->do_upload('single'))
{
// echo "<pre>";
// print_r($config1);
$images_path = './assets/Model/'.$this->upload->data('file_name');
$ins_up['model_id'] = $insert_id;
$ins_up['model_image'] = $images_path;
$result = $this->Paramodel->insert('model_image',$ins_up);
$this->_create_thumbs($this->upload->data('file_name'));
if($result == 1)
{
$this->session->set_flashdata('insert','Model Insert SuccessFully.');
redirect('manage-models');
}
}
else
{
$data['error'][$i] = array('error' => $this->upload->display_errors());
}
}
}
}
}
else
{
$data['error'][$i] = array('error' => $this->upload->display_errors());
}
}
}
}
$this->load->view('admin/add_model',$data);
}
my code is this try it.
I want to add $datasigned string value to the existing $data values, what should I do?
public function index(Request $request){
$data = Apidata::select('file')->where('nim','=',$request->nim)->get();
foreach($data as $berkas){
$url = $berkas->file;
$berkas = (array)$berkas;
// $filename = basename($url);
// $file = storage_path().'/berkas/'.$filename;
$pathfile = pathinfo($url);
$datasigned = $pathfile['dirname'].'/'.$pathfile['filename'].'_signed.'.$pathfile['extension'];
$berkas[]["file"] = $datasigned;
}
return $data;
}
I suppose that you are using laravel so maybe this will help you :
public function index(Request $request){
$data = Apidata::select('file')->where('nim','=',$request->nim)->get()->toArray();
foreach($data as $berkas){
$url = $berkas["file"];
// $filename = basename($url);
// $file = storage_path().'/berkas/'.$filename;
$pathfile = pathinfo($url);
$datasigned = $pathfile['dirname'].'/'.$pathfile['filename'].'_signed.'.$pathfile['extension'];
$berkas["file"]= $datasigned
}
return $data;
Or you can try :
public function index(Request $request){
$data = Apidata::select('file')->where('nim','=',$request->nim)->get();
foreach($data as $berkas){
$url = $berkas->file;
$berkas = (array)$berkas
// $filename = basename($url);
// $file = storage_path().'/berkas/'.$filename;
$pathfile = pathinfo($url);
$datasigned = $pathfile['dirname'].'/'.$pathfile['filename'].'_signed.'.$pathfile['extension'];
$berkas["file"] = $datasigned
}
return $data;
If you do not want to override "file" you can simply replace $berkas["file"] = $datasigned with $berkas[]["file"] = $datasigned
if you want to add it to data you have to create anew array is more simple do something like :
public function index(Request $request){
$data = Apidata::select('file')->where('nim','=',$request->nim)->get()->toArray();
$newDaata = [];
foreach($data as $berkas){
$url = $berkas["file"];
// $filename = basename($url);
// $file = storage_path().'/berkas/'.$filename;
$pathfile = pathinfo($url);
$datasigned = $pathfile['dirname'].'/'.$pathfile['filename'].'_signed.'.$pathfile['extension'];
$berkas["file"]= $datasigned
array_push($newData , $berkas);
}
return $newData;
Hope is yusefull
Thanks #Troaca Mihai!
public function index(Request $request){
$data = Apidata::select('file')->where('nim','=',$request->nim)->get()->toArray();
$newData = [];
foreach($data as $berkas){
$url = $berkas["file"];
// $filename = basename($url);
// $file = storage_path().'/berkas/'.$filename;
$pathfile = pathinfo($url);
$datasigned = $pathfile['dirname'].'/'.$pathfile['filename'].'_signed.'.$pathfile['extension'];
$berkas["file"]= $datasigned;
array_push($newData , $berkas);
}
$combinedData = array_merge($data,$newData);
return $combinedData;
}
i try with for loop,while loop, recursion...
nothing help.
maybe some pointers or memory-limit problems?
please help me :(
my code:
/*$arrImg = [['name'=>'some name', 'note'=> 'some url-image from ajax'],
['name'=>'some other name', 'note'=> 'some other url-image from
ajax']],...];*/
function saveMyImageFromString($string, $filename) {
$data = imagecreatefromstring(base64_decode(str_replace(' ', '+', $string)));
imagealphablending($data, false);
imagesavealpha($data, true);
imagepng($data, $filename);
imagedestroy($data);
unset($data);
}
$directory = 'img/';
$filename = 'deleteme.png';
$len = count($arrImg);
$iterationHeight = 0;
for ($i = 0; $i < $len; $i++) {
saveMyImageFromString($arrImg[$i]['note'], $directory . $i . $filename);
}
I need to upload files and folders into a course in moodle from a zip file, I have been searching and I found how to upload files. I try to upload, and the files are uploaded correctly into the database and in the file repository, but this files are not showed in the course when I enter to the course.
The code below is what I trying
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$context = context_course::instance($courseid);
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $context->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
I try to upload the files manually through the website and I've noticed that the folders ara created in another table called mdl_folder or in the table called mdl_file, but i don't know how do that and the best way to create and relate folders with files programatically for then displayed in the website well.
So if anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.
Thanks in advance.
I found a solution that works for me, I don't know if it is the most appropriate or not, if someone can take a look and tell me if it is correct or not, or what changes could make would be grateful.
The solution i found is:
Create or get it back the folder who will contain the files
Upload the files
Code:
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$folder = get_folder($courseid, 'Upload Test');
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $folder->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
And the function to create or get it back the folder is:
function get_folder($courseid, $resource_name) {
global $DB, $CFG;
//Comprobamos si la carpeta ya existe ya existe
$sql = "SELECT cm.id as cmid FROM {course_modules} cm, {folder} res
WHERE res.name = '" . $resource_name . "'
AND cm.course = " . $courseid . "
AND cm.instance = res.id";
if (! $coursemodule = $DB->get_record_sql($sql)) {
require_once($CFG->dirroot.'/course/lib.php');
echo "\tCreate new folder\n";
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
// get module id
$module = $DB->get_record('modules', array('name' => 'folder'), '*', MUST_EXIST);
// get course section
/*course_create_sections_if_missing($course->id, 0);
$modinfo = get_fast_modinfo($course->id);
$cw = $modinfo->get_section_info(0);
echo "section id: " . $cw->id;*/
$sectionid = $DB->get_record('course_sections', array('course' => $course->id, 'name' => 'Recursos'), '*', MUST_EXIST);
$folder_data = new stdClass();
$folder_data->course = $course->id;
$folder_data->name = $resource_name;
$folder_data->intro = '<p>'.$resource_name.'</p>';
$folder_data->introformat = 1;
$folder_data->revision = 1;
$folder_data->timemodified = time();
$folder_data->display = 0;
$folder_data->showexpanded = 1;
$folder_data->showdownloadfolder = 1;
$folder_id = $DB->insert_record('folder', $folder_data);
echo "folder id: " . $folder_id;
// add course module
$cm = new stdClass();
$cm->course = $courseid;
$cm->module = $module->id; // should be retrieved from mdl_modules
$cm->instance = $folder_id; // from mdl_resource
$cm->section = $sectionid->id; // from mdl_course_sections
$cm->visible = 1;
$cm->visibleold = 1;
$cm->showavailability = 1;
$cm->added = time();
$cmid = $DB->insert_record('course_modules', $cm);
// add module to course section so it'll be visible
if ($DB->record_exists('course_sections', array('course' => $courseid, 'section' => 1))) {
$sectionid = $DB->get_record('course_sections', array('course' => $courseid, 'section' => 1));
// if sequence is not empty, add another course_module id
if (!empty($sectionid->sequence)) {
$sequence = $sectionid->sequence . ',' . $cmid;
} else {
// if sequence is empty, add course_module id
$sequence = $cmid;
}
$course_section = new stdClass();
$course_section->id = $sectionid->id;
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->update_record('course_sections', $course_section);
} else {
$sequence = $cmid;
$course_section = new stdClass();
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->insert_record('course_sections', $course_section);
}
rebuild_course_cache($courseid, true);
// get context again, this time with all resources present
$context = get_folder($courseid, $resource_name);
return $context;
} else {
$context = context_module::instance($coursemodule->cmid);
return $context;
}
} // get_folder