Upload multiple pictures renaming files in Codeigniter 3 - file

I'm not able to figure out what's wrong in my code.
In my project the user is allowed to upload multiple pictures for each aircraft registration number; I want to rename each uploaded files with the following rules: registration id, minus sign, progressive number; so if the user upload a new image file for the registration id xxx, the uploaded filename becomes xxx-1.jpg
The code to upload the multiple files is the following; it works fine so far...
// Count uploaded files
$countfiles = count($_FILES['files']['name']);
// Define new image name
$image = $id . '-1.jpg';
for($i=0;$i<$countfiles;$i++)
{
if(!empty($_FILES['files']['name'][$i]))
{
// Define new $_FILES array - $_FILES['file']
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// Check if the image file exist and modify name in case
$filename = $this->_file_newname($uploaddir,$image);
// Set preference
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '5000';
$config['file_name'] = $filename;
//Load upload library
$this->load->library('upload',$config);
$arr = array('msg' => 'something went wrong', 'success' => false);
// File upload
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
}
}
}
The _file_newname() function does the file renaming jog, here you are the code:
private function _file_newname($path, $filename)
{
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.$filename;
$newname = $filename;
if(file_exists($newpath)){
$counter = 1;
if($pos = strrpos($name, '-')) {
$oldcounter = substr($name, $pos + 1);
if(is_numeric($oldcounter)){
$counter = $oldcounter++;
$name = substr($name, 0, $pos);
}
}
$newname = $name . '-' . $counter . $ext;
$newpath = $path . $newname;
while (file_exists($newpath)) {
$newname = $name .'-'. $counter . $ext;
$newpath = $path.$newname;
$counter++;
}
}
return $newname;
}
Now...the issue....the renaming function works fine if the user upload one file each time...so the first upload set the file name xxx-1.jpg, the second upload set the filename to xxx-2.jpg and so on....but....if the user upload more then one file at time...the second file become xxx-1x.jpg.
If already exists one file on server ( for example xxx-1.jpg ) and the user upload two more files..they are renamed as xxx-2.jpg ( correct) and xxx-21.jpg (wrong...should be xxx-3.jpg).
Any hint or suggestion to fix the issue?
Thanks a lot

Your new file name is out of the loop for the uploaded photos.
So it becomes static.
Put that line inside the loop:
// Define new image name
$image = $id . '-' . $i . '.jpg';
This way you are gonna keep the $id and rename the files according to the iteration of the loop - $i.

Related

Typo3 download remote files and create a file object

How do I save a remote file to local storage in Typo3 v10.
Having the following code, no files are getting saved in fileadmin storage
private function saveFileFromUri($fileUrl)
{
$urlParts = parse_url($fileUrl);
$pathParts = pathinfo($urlParts['path']);
$fileName = $pathParts['basename'];
$file = GeneralUtility::getUrl($fileUrl);
$temporaryFile = GeneralUtility::tempnam('temp/' . $fileName);
$storage = $this->defaultStorage->createFolder($pathParts['dirname']);
if ($file === false) {
$error = sprintf(
'File %s could not be fetched.',
$fileUrl
);
if (isset($report['message'])) {
$error .= ' ' . sprintf(
'Reason: %s (code: %s)',
$report['message'],
$report['error'] ?? 0
);
}
throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
$error,
1613555057
);
}
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($file);
GeneralUtility::writeFileToTypo3tempDir(
$temporaryFile,
$file
);
$fileObject = $storage->addFile(
$temporaryFile,
$storage,
$fileName
);
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($fileObject);
}
What is the right way to save remote files in typo3 and create a fileObject?
TYPO3 has an API to get or add files via the File Abstraction Layer (FAL).
This example adds a new file in the root folder of the default storage:
$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
$storage = $storageRepository->getDefaultStorage();
$newFile = $storage->addFile(
'/tmp/temporary_file_name.ext',
$storage->getRootLevelFolder(),
'final_file_name.ext'
);
Please refer to the documentation for details.

Get file information form directory Laravel

I use the following method to get all files from a folder and my method returns some basic information about the files inside directory
public function getUploaded()
{
$files = [];
$filesInFolder = File::files(base_path() .'/'. self::UPLOAD_DIR);
foreach($filesInFolder as $path)
{
$files[] = pathinfo($path);
}
return response()->json($files, 200);
}
How would I get the size and the base name like ?
$files['name'] = ....
$files['size'] = ....
You could solve this quite neatly with a Laravel collection and SplFileInfo. Something along the following lines;
public function getUploaded()
{
$files = collect(File::files(base_path() . "/" . self::UPLOAD_DIR))->map(function ($filePath) {
$file = new \SplFileInfo($filePath);
return [
'name' => $file->getName(),
'size' => $file->getSize(),
];
});
return response()->json($files);
}
You can modify your code as follows:
foreach ($filesInFolder as $path) {
$file = pathinfo($path);
$file['size'] = File::size($path);
$file['name'] = File::name($path);
$files[] = $file;
}

My photo gallery I upload multiple image with encrypted name, But I want to save these encrypted name in database

My codeigniter photo gallery upload multiple image in single click. Image upload with encrypted name but name save in database original image name.I want to save in database those encrypted name.
My controller code is:
public function file_upload2(){
if($this->session->userdata('is_loged_in')){
$config = array();
$config['image_library'] = 'gd2';
$config['upload_path'] = './photo/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|JPG';
$config['max_size'] = 0;
$config['maintain_ratio'] = FALSE;
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$this->form_validation->set_rules('category', 'Category', 'required|trim');
if ($this->form_validation->run() == TRUE){
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++){
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$category = $this->input->post('category');
$fileName = implode(',',$images);
$this->Upload_model->upload_image($fileName,$category);
if($this->upload->do_upload()){
$this->success();
} else {
$this->index();
}
} else {
$this->index();
}
} else {
redirect('admin');
}
}
My Model:
public function upload_image($fileName,$category){
if($fileName!='' ){
$filename1 = explode(',',$fileName);
foreach($filename1 as $file){
$file_data = array(
'name' => $file,
'datetime'=> date('Y-m-d h:i:s'),
'category'=> $category
);
$this->db->insert('photo', $file_data);
}
}
}
When you uploading, use the codeigniter's upload data, since php $_FILES array doesn't know anything about the encrypted name:
if ($this->upload->do_upload()) {
$data = $this->upload->data();
echo $data['file_name']; // Here is the encrypted filename
}

upload a file in cakePHP

Hi I want to upload a file using cake php, i got the file and i am using
move_uploaded_file() to move to a specific location but it is not moving my simple logic is
shown below
if (move_uploaded_file($this->data['Add']['upload']['tmp_name'], APP . 'views' . DS .
'static' . DS.'uploads'.DS.'Rajaram'.DS )) {
LogUtil::$logger->debug('KMP File upload Url :
'.var_export($this->data, true));
}
Thanks in Advance.
File uploading is something CakePHP doesn’t do out of the box, which is one of the only thing that annoys me about the framework.
I tackled this by adding file handling to a model using callback methods. I upload the actual file with beforeSave(), and delete the file from the file system with beforeDelete(). A sample model looks like this:
<?php
App::uses('File', 'Utility');
class Image extends AppModel {
public $name = 'Image';
public function beforeSave($options = array()) {
$fieldName = 'filename';
$field = $this->data[$this->alias][$fieldName];
if (!is_array($field)) {
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
}
switch ($field['error']) {
case UPLOAD_ERR_OK:
$newFilename = time() . '.jpg';
$uploadDir = WWW_ROOT . 'files/';
$source = $field['tmp_name'];
$destination = $uploadDir . $newFilename;
if (move_uploaded_file($source, $destination)) {
$this->data[$this->alias][$fieldName] = $newFilename;
return true;
}
else {
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
}
break;
default:
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
break;
}
}
public function beforeDelete($cascade = true) {
$image = $this->findById($this->id);
$file = new File(WWW_ROOT . 'files/' . $image['Image']['filename']);
return $file->delete();
}
}
Obviously this isn’t a perfect implementation, so feel free to take from it, learn from it, adapt it.
This was written off-the-cuff for a project recently where there’s only one model that has images attached, but on a larger project I’d more than likely wrap it up into a nice model behavior.
In your model you can use the afterSave callback method to handle your file upload:-
public function afterSave($created) {
if (isset($_FILES['data']['name'][$this->alias]['filename'])) {
$filename = $_FILES['data']['name'][$this->alias]['filename'];
$fileInfo = pathinfo($filename);
$fileExt = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
$filename = $fileInfo['filename'];
$newFilename = "$filename.$fileExt";
$dir = WWW_ROOT . 'files' . DS . 'uploads';
$target = $dir . DS . $newFilename;
move_uploaded_file($source, $target);
}
}
You can use $newFilename to change the filename to something appropriate if need be (I tend to check if a file with the same name already exists and rename the new one to avoid overwriting it.

cakephp - Save file syncronized and send as attachment

Hi have a strange problem with File::write() in cakephp.
I write this code to generate a pdf view and save it on a file.
private function generate( $id ){
$order = $this->Order->read( null, $id );
$this->set('order', $order);
$view = new View($this);
$viewdata = $view->render('pdf');
//set the file name to save the View's output
$path = WWW_ROOT . 'ordini/' . $id . '.pdf';
$file = new File($path, true);
//write the content to the file
$file->write( $viewdata );
//return the path
return $path;
}
I need generate this pdf and send it as attacchment so, this is my code
public function publish ($id) {
$pdf_file = $this->generate( (int)$id );
$Email = new CakeEmail();
$Email->from(array('info#.....com' => '......'));
$Email->to('....#gmail.com');
$Email->subject('Nuovo ordine');
$filepath = WWW_ROOT . 'ordini/' . $id . '.pdf';
$Email->attachments(array('Ordine.pdf' => $filepath));
$Email->send('......');
}
The first time i run this code the email doesn't works, the email works nice only if the pdf is alredy in the folder.
I think that File::write perform some kind of async writing and when system execute Email::attachments the file ins't ready.
How can i insert a while() in this code to check file avability?
thanks a lot.
if($file->write( $viewdata ))
{
return $path;
}
using the return value wasn't enough.
I changed this line
$file = new File($path, false);
Opening file without forcing worked for me.

Resources