want to change image in codeigniter - image

I want to change an image in Codeigniter, replace the previously uploaded image and also delete previous image from folder :
Here is my Controller . But its not working:
public function changeImage(){
//$user_id = $this->profile_model->changeImage();
/************* File Upload ************/
$config['upload_path'] = './uploads/user_pic/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload',$config);
$filetype = $_FILES['user_pic']['type'];
$file_name = $_FILES['user_pic']['name'];
if($filetype == "image/jpg")
$file_type='jpg';
else if ($filetype == "image/gif")
$file_type='gif';
else if($filetype == "image/jpeg")
$file_type='jpg';
else if($filetype == "image/pjpeg")
$file_type='pjpeg';
else if($filetype == "image/png")
$file_type='png';
$_FILES['user_pic']['name']=$user_id.'.'.$file_type;
$this->upload->do_upload('user_pic');
$up_dtat = array('user_pic' => $_FILES['user_pic']['name']);
$this->db->where('user_id',$user_id);
$this->db->update('tbl_users',$up_dtat);
redirect('profile');
}

if you need to update the profile picture in your store file, first you need to remove the old file, fetch the old file name on the bases of user id.
Then give the file name with this code.
unlink("your_path/filename.jpg"); //don't use base_url() just give the path like profile_pic/xxxxx.png
This code will delete the specified file from that folder.
Now i have code that i had use for the file uploads so it will also work for you try this.
$imgpath='uploads/profile_pic/';//path where do you want to store image
$all_img="";
if($_FILES["profile_pic"]['name'])//input type that you have use in file upload
{
$path_parts = pathinfo($_FILES["profile_pic"]["name"]);
$image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension'];
$all_img.=$image_path;
move_uploaded_file($file_tmp=$_FILES["profile_pic"]["tmp_name"],$imgpath."/".$image_path);
$data['cm_user_profile_pic']=$all_img;//store filename in array to update in database
}

If you want to replace the previous image only but set file name same then
First method is :
get old file name from table
$sql = "SELECT user_pic FROM tbl_users WHERE user_id=?";
$get_image = $this->db->query($sql,array($user_id))->row_array();
set new file name as assigned to old
$config['file_name'] = $get_image['user_pic'];
$config['overwrite'] = TRUE; // this will overwrite your image
$this->load->library('upload', $config);
But in this case, old file and new file extension must be same
If both extensions are different then maybe image will be crashed after upload
The second method is
Get user_pic data from DB
And Unlink that picture
unlink($_SERVER['DOCUMENT_ROOT'].'/'.Your_image_folder.$get_image['user_pic']);
And check file is upload or not
if ( ! $this->upload->do_upload('user_pic')) {
$error = array('error' => $this->upload->display_errors());
}
else {
$data = array('upload_data' => $this->upload->data());
}

Related

laravel Backpack Original Image Name

I am using laravel backpack for my site and i need to upload some images, i copy the code from their website and works fine, but i need the original name on the images, i tried some things, but is not working.
public function setImageAttribute($value)
{
$attribute_name = "image";
$disk = "uploads";
$destination_path = 'storage/services/' .date('FY').DIRECTORY_SEPARATOR;
if ($value==null) {
Storage::disk($disk)->delete($this->{$attribute_name});
// set null in the database column
$this->attributes[$attribute_name] = null;
}
if (str_starts_with($value, 'data:image'))
{
$file = $value;
$filename = $this->generateFileName($file, $destination_path);
$image = InterventionImage::make($file)->orientate();
$fullPath = $destination_path.$filename.'.'.$file->getClientOriginalExtension();
$this->attributes[$attribute_name] = $fullPath;
}
protected function generateFileName($file, $destination_path)
{
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename = Str::random(20);
while (Storage::disk('uploads')->exists($destination_path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
return $filename;
}
why value alwys take image base64
is there any way to git image original name?
As far as I know, you won't be able to retrieve the filename, as it's always a base64 file. But maybe this work around helps you:
Image fields blade file can be found at:
\vendor\backpack\crud\src\resources\views\crud\fields\image.blade.php
You can overwrite it by making a file on the same name at:
\resources\views\vendor\backpack\crud\fields\image.blade.php
You can change anything there, maybe you can add a hidden input with the file name.

Intervention\Image\Exception\NotWritableException Can't write image data to path

I'm trying to put a image on a folder than i generate with a timestamp.
This give me the error in the title.
Intervention\Image\Exception\NotWritableException
Can't write image data to path (/Users/me/Sites/test/public/uploads/images/1573905600/title-1.jpg)
This is my code :
$photoPaths = $request->get('photo_paths');
if (isset($photoPaths)){
$photos = explode(';', $photoPaths);
$path = storage_path('tmp/uploads/');
$newPath = public_path('/uploads/images/').strtotime('12:00:00')."/";
$arrayPhoto = array();
foreach($photos as $photo){
$photoPath = $path . $photo;
if (File::exists($photoPath)) {
$newPhotoName = Str::slug($request->get('titre')."-".$i,"-").".jpg";
$newPhotoFullPath = $newPath . $newPhotoName;
$photo = Image::make($photoPath);
// $photo->resize(1400, 1050);
$photo->resize(null, 1050, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$photo->encode('jpg', 85);
if(!Storage::disk('public')->has($newPath)){
Storage::disk('public')->makeDirectory($newPath); //It seems it doesn't work
}
$saved = $photo->save($newPhotoFullPath); //Create the Exception
}
}
}
What i am doing wrong ?
Thanks
check this that this folder is already created or not.
then give it permission to write
sudo chmod -R 666 /public/upload/images //give permission your choice either it 666 or 775 or 777
and
$newPath = public_path('/uploads/images/').strtotime('12:00:00')."/";
if (!file_exists($newPath)) {
mkdir($newPath, 0755);
}
Check out this line of code
$newPhotoName = Str::slug($request->get('titre')."-".$i,"-").".jpg";
is it suppose to be
$newPhotoName = Str::slug($request->get('title')."-".$i,"-").".jpg";
I mean $request->get('title') instead of $request->get('titre').
OR
You can check out your input name from blade against your request validation and also your model fillable if they are same.
I hope this helps.

Create table using CSV header in laravel 5.4

I want to create a table using CSV file header when I upload a file.
If table does not exists then create table using CSV header
else just import data into a specified table.
This is my file upload code.
if($request->hasFile('file'))
{
$this->validate($request, ['file' => 'mimes:txt,xls,tsv,xlsx' ]);
//Get original file name
$filename = $request->file->getClientOriginalName();
//Get original file extention
$fileExtention = $request->file->getClientOriginalExtension();
//get upload user id
$uploadedUserId = Auth::user()->id;
//get file upload timestamp in microseconds
$microseconds = microtime(true);
//remove special characters from file name
$sansSpecial = preg_replace('/[\'\"\,\(\)\s]/', '_',$filename);
//prepend timestamp to modified file name
$prependTimestamp = $microseconds.'-'.$sansSpecial;
//create unique hash code from modified file name
$uniqueFileHash = Hash::make($prependTimestamp);
$uploadDirectory ='/app/public';
$uploadPath = storage_path().$uploadDirectory;
if(Storage::exists('./public/'.$filename))
{
Use the path info helper function to get file info.
$fileInfo= pathinfo($filename);
//Add timestamp to file if file already exist.
$finsert = $fileInfo['filename'].date('(m-d-y h i s)').'.'.$fileExtention;
//Store file into directory.
$insert = $request->file->storeAs('./public/',$finsert);
//New upload object.
$file = new Upload;
//Assign new file name
$file->file_name = $finsert;
//Assign new modiefied file name with prepended timestamp
$file->modified_file_name = $prependTimestamp;
//Assign unique file hash.
$file->unique_file_hash = $uniqueFileHash;
//Assign full file path
$file->file_full_path = $uploadPath;
//Assign uploaded user id
$file->uploaded_user_id = $uploadedUserId;
//Store all informamation into database.
$file->save();
}

Laravel returns uploaded file instead of it path

I am uploading a file and saving it in local storage. These files are stored in the database related to a particular user. When i return the last saved user. I get other details in response properly. But instead of the file path. I get the file as response
$file = $request->file('resume');
$profile_id = $request['profile_id'];
$original_name = $_FILES['resume']['name'];
$resume_new_name = str_random(). '.' . $file->getClientOriginalExtension();
$new_file = $request->file('resume')->move('resources/assets/resumes',$resume_new_name);
$candidate_info['resume'] = $new_file;
$candidate = new candidate();
if (empty($candidate_info['name'])) {
$candidate_info['name'] = $candidate_info['email'];
}
$candidate->name = $candidate_info['name'];
$candidate->phone = $candidate_info['phone'];
$candidate->email = $candidate_info['email'];
$candidate->resume = $candidate_info['resume'];
$candidate->client_id = \Auth::user()->id;
$candidate->status = "new";
$candidate->profile_id = $profile_id;
$candidate->save();
return response()->json(['msg' => $candidate]);
In database column 'resume' it stores the path. But in json response it sends the whole file instead of the path. how do i send the path instead of sending the whole file
Just return the value of that one column:
return response()->json(['msg' => $candidate->resume]);
Instead of using move use store
$new_file = $request->file('resume')->store('resources/assets/resumes',$resume_new_name);

multi image upload in custom component for joomla

I have tried http://docs.joomla.org/Creating_a_file_uploader_in_your_component but first it shows Error: 500 after some research I have removed code
"'.$session->getName().'" : "'.$session->getId().'",
"format" : "raw"
and error is gone. Now Image is not uploading anywhere (I have set path '/images/' folder) I am confuse in code for uploading image PART 5 where to use this code?
function storeImageFile()
{
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder' );
$path = 'PATH_GOES_HERE'.'designs'.DS;
$folder_permissions = "0755";
$folder_permissions = octdec((int)$folder_permissions);
//create folder if not exists
if (!JFolder::exists($path)){
JFolder::create($path, $folder_permissions);
}
$file = JRequest::getVar('design_images', null, 'files',
$count = count($file['name']);
for($i=0;$i<$count;$i++)
{
//$i is the array position of the $_FILES array
if(empty($file['tmp_name'][$i]))
{
return false;
}
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name'][$i]);
//setting source and destination
$temporary_name = $file['tmp_name'][$i];
$filename = str_replace(' ', '_', $file['name'][$i]);
$dest = $path.$filename;
if(JFile::upload($temporary_name, $dest))
{
echo "File Upload Successful";
return true;
}
}
}

Resources