Magento2 read uploaded csv file - file-upload

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.
}
}

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.

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.

How do I read multiple files after click opened in OpenFileDialog?

I have set a multiselect function in my code to allow me to open multiple files which is in ".txt" forms. And here is the problem, how am I going to read all these selected files after it opened through OpenFileDialog? The following codes and at the "for each" line, when I use System::Diagnostics::Debug, it shows only the data from a file, while data of other files were missing. How should I modify the code after the "for each"? Can anyone provide some suggestions or advice? The files selected are as 1_1.txt, 2_1.txt, 3_1.txt. Appreciate your reply and Thanks in advance.
Here is my written code,
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Title = "open captured file";
openFileDialog1->Filter = "CP files (*.cp)|*.cp|All files (*.*)|*.*|txt files (*.txt)|*.txt";
openFileDialog1->FilterIndex = 2;
openFileDialog1->Multiselect = true;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
array<String^>^ lines = System::IO::File::ReadAllLines(openFileDialog1->FileName);
for each (String^ line in lines) {
//?????
System::Diagnostics::Debug::WriteLine("",line);
}
}
You need to look at the OpenFileDialog.FileNames property if you allow multiple files to be selected:
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
for each (String^ file in openFileDialog1->FileNames)
{
array<String^>^ lines = System::IO::File::ReadAllLines(file);
for each (String^ line in lines)
{
System::Diagnostics::Debug::WriteLine("",line);
}
}
}
Use the FileNames property.
C# version (should be easy to adapt for C++):
foreach (var file in openFileDialog1.FileNames)
{
foreach (var line in File.ReadAllLines(file)
{
...
}
}
Use openFileDialog1->FileNames. It returns the multiple filenames that you selected
Read here
http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.multiselect.aspx
its in C# but, it will be easy to extrapolate to C++.

Create a zip file from a list of selected files and make the zipped file downloadable in Drupal 7

I have a list of image files. I need to archive those files in zip format and make the archived file downloadable. I have seen ArchiverZip class defined in the system module of Drupal 7. But I couldn't be able to create a zip file. How can I do this in Drupal 7 ? Is there any hooks or custom modules for this ? Please help me out with this.
UPDATED
Following are the codes:
$zip = new ArchiverZip('archive.zip');
foreach($_POST['img'] as $fid):
$query = db_select('file_managed', 'fn')
->condition('fid', $fid)
->fields('fn', array('filename'));
$result = $query->execute();
foreach($result as $row) {
if(file_exists('sites/default/files/'.$row->filename)){
var_dump($zip->add($base_path.'sites/default/files/'.$row->filename));
}
}
endforeach;
And this reflects the following error
Exception: Cannot open archive.zip in ArchiverZip->__construct() (line 91 of basepath\modules\system\system.archiver.inc).
Please help me with this . .
Well I missed to create the archive.zip file before creating the ArchiverZip class so the archiving operation failed previously . . Now the code will be like below:
$filename = 'archive.zip';
fopen($filename, 'w');
$zip = new ArchiverZip($filename);
foreach($_POST['img'] as $fid):
$query = db_select('file_managed', 'fn')
->condition('fid', $fid)
->fields('fn', array('filename'));
$result = $query->execute();
foreach($result as $row) {
if(file_exists('sites/default/files/'.$row->filename)){
$zip->add($base_path.'sites/default/files/'.$row->filename);
}
}
endforeach;