Yii2 - rename file on upload if the file with the same name exist - yii

How can I rename file if the file with the same name exist (prevent overwrite)? This method is used for uploading file:
// Upload user avatar
public function upload()
{
if ($this->validate()):
$this->avatar->saveAs('../web/images/avatars/' . $this->avatar->baseName . '.' . $this->avatar->extension);
return true;
endif;
return false;
}

Test if file exists with php function and then assign a proper name to your file:
$cnt = 1;
while (file_exists(string $filename)) {
$filename = $this->avatar->basename . $cnt;
$cnt++;
}
Then save.

Related

laravel 7 pdf-to-text | Could not read pdf file

I installed this laravel package to convert pdf file into text. https://github.com/spatie/pdf-to-text
I'm getting this error:
Could not read sample_1610656868.pdf
I tried passing the file statically by putting it in public folder and by giving path of uploaded file.
Here's my controller:
public function pdftotext(Request $request)
{
if($request->hasFile('file'))
{
// Get the file with extension
$filenameWithExt = $request->file('file')->getClientOriginalName();
//Get the file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//Get the ext
$extension = $request->file('file')->getClientOriginalExtension();
//File name to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload File
$path = $request->file('file')->storeAS('public/ebutifier/pdf', $fileNameToStore);
}
// dd($path);
$location = public_path($path);
// $pdf = $request->input('file');
// dd($location);
// echo Pdf::getText($location, 'usr/bin/pdftotext');
$text = (new Pdf('public/ebutifier/pdf/'))
->setPdf($fileNameToStore)
->text();
return $text;
}
Not sure why it's not working any help would be appreciated.
You used spatie/pdf-to-text Package.
I also tried to use this package but it gave me this kind of error.
So, I used asika/pdf2text package and it worked properly
Asika/pdf2text pacakge
And this is my code
$path = public_path('/uploads/documents/'. $file_name);
$reader = new \Asika\Pdf2text;
$output = $reader->decode($path);
dd($output);
Hopefully, it will be helpful for you.

Magento2 read uploaded csv file

I have upload CSV file but problem is i don't know how to read data of uploaded csv file in Magento2.
Please help me anyone.
Thanks in advance.
You can do that like you could in Magento 1. In Magento 1 you would use
new Varien_File_Csvbut in Magento 2 you can do the same with \Magento\Framework\File\Csv. You can use the following code.
In your __construct() inject the following classes:
protected $_fileCsv;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Module\Dir\Reader $moduleReader,
\Magento\Framework\File\Csv $fileCsv
) {
$this->_moduleReader = $moduleReader;
$this->_fileCsv = $fileCsv;
parent::__construct($context); // If your class doesn't have a parent, you don't need to do this, of course.
}
Then you can use it like this:
// This is the directory where you put your CSV file.
$directory = $this->_moduleReader->getModuleDir('etc', 'Vendor_Modulename');
// This is your CSV file.
$file = $directory . '/your_csv_file_name.csv';
if (file_exists($file)) {
$data = $this->_fileCsv->getData($file);
// This skips the first line of your csv file, since it will probably be a heading. Set $i = 0 to not skip the first line.
for($i=1; $i<count($data); $i++) {
var_dump($data[$i]); // $data[$i] is an array with your csv columns as values.
}
}

file name automatically change when i upload the file

I'm new to CodeIgniter and having the following issue. When I upload a file, its successfully uploaded on my local folder and the file name saved to the db. The problem is, file name has been changed after uploading.
eg:
file name "screenshot image 123.png" -> "screenshot_image_123.png"
It just convert the space into underscore;this issue occurred only when the file name having space.Other than this issue all the other files uploading successfully. Given below is my code which I used on my controller page:
public function upload_pic()
{
$image_path = realpath(APPPATH . '../uploads');
$config['upload_path'] = $image_path;
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['file_name'] = $_FILES['file']['name'];
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('file'))
{
echo $this->upload->display_errors();
}
else
{
$finfo=$this->upload->data();
$data['uploadInfo'] = $finfo;
}
}
Can anyone help me????
Try before saving file name generate some unique
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$filename = sha1_file($filename). md5(date('Y-m-d H:i:s:u')) . '.'. $ext; //not only this you can generate any format
$config['file_name'] = $filename; //Use this file name is db too

yii2 fixtures doesn't work properly

I have a problem with fixtures in yii2 , I just created all required file according to this document but it's not working.
let me explain , I have a module called Authyii and inside this module I have a model named User .
this is my directory structure :
my fixture file is like this :
namespace app\modules\Authyii\tests\fixtures;
use app\modules\Authyii\models;
use yii\test\ActiveFixture;
use yii\test\Fixture;
class UserFixture extends ActiveFixture
{
public $modelClass = 'app\modules\Aythyii\models\User';
public $tableName = 'authyii_user';
}
this is my command line :
but after I type 'yes' and command line says :
but when I check my database there is not new record inside authyii_user tables .
what I missed ?
File User.php id data dir must have table name authyii_user.php. In framework source code in file ActiveFixture.php line with code:
$dataFile = dirname($class->getFileName()) . '/data/'
. $this->getTableSchema()->fullName . '.php';
Best regards.
There is method getFixturesConfig() in \vendor\yiisoft\yii2\console\controllers\FixtureController.php
private function getFixturesConfig($fixtures)
{
$config = [];
foreach ($fixtures as $fixture) {
$isNamespaced = (strpos($fixture, '\\') !== false);
$fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture';
if (class_exists($fullClassName)) { // <<< I think you lose your UserFixture here
$config[] = $fullClassName;
}
}
return $config;
}
You should check what $fullClassName Yii expects it to be (for example logging or echoing it) and tweak your UserFixture's namespace accordingly.

Can anyone help me with this error

if (isset($_POST['Software'])) {
$_POST['Software']['sw_icon'] = $model->sw_icon;
$model->attributes = $_POST['Software'];
$uploadedFile = CUploadedFile::getInstance($model, 'sw_icon');
$model->attributes = $_POST['Software'];
$model->updated_date = date("Y-m-d H:i");
if ($model->save()) {
if (!empty($uploadedFile)) { // check if uploaded file is set or not
$uploadedFile->saveAs(Yii::app()->basePath . '/../images/software_icons/' . $model->sw_icon);
}
Yii::app()->user->setFlash('success', 'Software updated successfully.');
$this->redirect(array('index'));
}
}
When I use the above code i get the following error
...move_uploaded_file(): The second argument to copy() function
cannot be a directory.
Can you show me the result of Yii::app()->basePath . '/../images/software_icons/' . $model->sw_icon,seems like it a directory
You can move a file to another file name. You can't move a file to a folder.
Try replace Yii::app()->basePath . '/../images/software_icons/' . $model->sw_icon on
this: Yii::app()->basePath . '/../images/software_icons/newfile'