Hi Here i am using CActiveFrom fileField to upload the file in the server but the pdf files not saving remaining all the extensions are saving here is my controller code to save the file
controller
if(isset($_POST['Uploadinfo']))
{
$model->attributes=$_POST['Uploadinfo'];
$file = CUploadedFile::getInstance($model, 'imageId');
$model->imageId=CUploadedFile::getInstance($model, 'imageId');
$valid = $model->validate();
date_default_timezone_set('Asia/Kolkata');
$serverTime = date("Y-m-d H:i:s", time());
if(!empty($file->name) && $valid)
{
$modelFileLocation->filename = microtime() . $file->name;
$modelFileLocation->orgfilename = $file->name;
$modelFileLocation->type = 1;
$modelFileLocation->createdOn = $serverTime;
$modelFileLocation->lastModifiedBy = 'lecturer';
$valid = $modelFileLocation -> validate();
$modelFileLocation->deptId = $_POST['Uploadinfo']['departmentId'];
print_r($file);
if ($modelFileLocation->save())
{
$file = CUploadedFile::getInstance($model, 'imageId');
print_r($modelFileLocation);
print_r($file);
die();
$model->userId = $_POST['Uploadinfo']['userId'];
$model->imageId = $modelFileLocation->id;
$model->departmentId = 1;
$model->createdOn = $serverTime;
$model->lastModifiedBy = 'lecturer';
if ($model->save())
{
$modeldocumentinfo->property = $file->type;
$modeldocumentinfo->fileName = $modelFileLocation->filename;
$modeldocumentinfo->creator = 'lecturer';
$modeldocumentinfo->lastUploadedOn = $serverTime;
$modeldocumentinfo->uploadId = $model->id;
$modeldocumentinfo->viewers = 0;
$modeldocumentinfo->save();
$file->saveAs('uploads/files/' . $modelFileLocation->filename);
print_r($file);
die();
//Yii::app()->user->setFlash('uploadsuccess', "File Uploaded Successfully...");
$this->redirect(array('lmaterialitview'));
}
}
in above code i print the instance of file before and after the $modelFileLocation model saving before this model is saving the file instance is getting but after this saving the model the file instance getting empty
here is the instance code
instance message
CUploadedFile Object ( [_name:CUploadedFile:private] => example.pdf [_tempName:CUploadedFile:private] => C:\wamp\tmp\php4BB.tmp [_type:CUploadedFile:private] => application/pdf [_size:CUploadedFile:private] => 205374 [_error:CUploadedFile:private] => 0 [_e:CComponent:private] => [_m:CComponent:private] => )
and in the second print_r() it is disappering but for remaining extensions it is getting appear and saving
just set the $deleteTempFile argument to false
$file->saveAs('uploads/files/' . $modelFileLocation->filename, false);
Related
i'm new in phbp and yii and i have a pronblem with sendind file, i'm using kartik\file\FileInput widget without model and i send to yii controller, where i can get my file from $POST and in first time i used move_uploaded_file with linkt to my file on tmp. The first idea with move doesnt work, i wouldnt find my file on disk, i know is systemd, but i change my tmp folder in php.ini but the file from form doesnt show in this place. This is my conbtroller
$output = "";
$modelZalaczniki = new DelegacjeZalacznikiSearch();
$modelZalaczniki->d_add = date('Y-m-d H:i:s');
$modelZalaczniki->u_add = Yii::$app->user->identity->id;
if (empty($_FILES['file'])){
echo json_encode(['error'=>'Nie znaleziono plik.w.']);
return;
}
$files = $_FILES['file'];
$success = null;
$paths = [];
$fileNames = $files['name'];
if(!file_exists('uploads')){
mkdir('uploads', 0750, true);
}
if(!file_exists('uploads'.DIRECTORY_SEPARATOR.'delegacje')){
mkdir('uploads'.DIRECTORY_SEPARATOR.'delegacje', 0750, true);
}
if(!file_exists('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki')){
mkdir('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki', 0750, true);
}
if(!file_exists('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki'.DIRECTORY_SEPARATOR.$delegacja_id)){
mkdir('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki'.DIRECTORY_SEPARATOR.$delegacja_id, 0750, true);
}
for($i = 0; $i < count($fileNames); $i++){
$ext = explode('.', basename($fileNames[$i]));
$hashName = md5($fileNames[$i]);
$target = 'uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki'.DIRECTORY_SEPARATOR.$delegacja_id.DIRECTORY_SEPARATOR.$hashName;
// if(file_exists($target)){
// $success = true;
// break;
// }
if(move_uploaded_file($files['tmp_name'][$i], $target)){
$success = true;
$paths[] = $target;
$modelZalaczniki = new DelegacjeZalaczniki();
$modelZalaczniki->delegacja_id = $delegacja_id;
$modelZalaczniki->d_add = date('Y-m-d H:i:s');
$modelZalaczniki->u_add = Yii::$app->user->identity->id;
$modelZalaczniki->sciezka = $target;
$modelZalaczniki->nazwa = $fileNames[$i];
$modelZalaczniki->typ = $ext[1];
$modelZalaczniki->size = $files['size'][$i];
if ($modelZalaczniki->validate()){
$modelZalaczniki->save();
}
}else{
$success = false;
break;
}
Every things work fine but i cant move file to my folder, aha, file is create but in this file is linkt to yii documentation.
Yii 2.0 is great at uploading files. No need for move_uploaded_file.
Take a look at the documentation, and specifically the UploadedFile::getInstance() method.
Useful examples which are relevant to what you're doing are here:
https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
In the above code, when the form is submitted, the yii\web\UploadedFile::getInstance() method is called to represent the uploaded file as an UploadedFile instance. We then rely on the model validation to make sure the uploaded file is valid and save the file on the server.
I'm create project CRUD with uploads file using json_encode for uploads file in database. i want to ask how to edit/update json field in database laravel ?
i try using isset($data)? json_encode($data): $sid->file_uploads in public function update() but that code when i update can be replace previous file.
$sid = Sid::find($id);
if($request->file('file_uploads'))
{
foreach($request->file('file_uploads') as $file)
{
$name = $file->getClientOriginalName();
$path = 'public/file/'.$sid->employee_name;
$file->move($path, $name);
$data[] = $name;
}
}
$sid->employee_sid = $request->employee_sid;
$sid->employee_npk = $request->employee_npk;
$sid->employee_name = $request->employee_name;
$sid->file_uploads = isset($data)? json_encode($data): $sid->file_uploads;
$sid->save();
i expect the result is file when i upload will add file in DB. for example i uploads 5 file but when i create i just uploads 2 file and when i want to edit i add 3 file and totals file is 5 in DB.
This can resolve, php in the new versions does not support creation of var at runtime, or its if that checks if it has files is resulting in false.
$sid = Sid::find($id);
$data = [];
if($request->file('file_uploads'))
{
foreach($request->file('file_uploads') as $file)
{
$name = $file->getClientOriginalName();
$path = 'public/file/'.$sid->employee_name;
$file->move($path, $name);
$data[] = $name;
}
}
$sid->employee_sid = $request->employee_sid;
$sid->employee_npk = $request->employee_npk;
$sid->employee_name = $request->employee_name;
$sid->file_uploads = count($data)? json_encode(array_merge(json_decode($sid->file_uploads, true),$data)): $sid->file_uploads;
$sid->save();
I've used PSR logger to get logs. But it will create just one file for all dates. I need to get separate log files to each date. How to do that?
require_once '../../logger/vendor/autoload.php';
require_once '../../logger/Psr/Log/Logger.php';
use Katzgrau\KLogger\Logger;
use Psr\Log\LogLevel;
$logPath = '/var/www/html/logs';
$logger = new Logger($logPath, LogLevel::DEBUG, array ( 'filename' => 'driver_api' , 'extension' => 'log' ));
$logger->log( $level, $message , $context);
`
use log rotator
protected function log_rotate($logpath, $filename, $extention){
$logfilename = $logpath.'/'.$filename.'.'.$extention; //not needed when included
$logfilestokeep = 15;
$fileDate = '';
if (file_exists($logfilename)) {
if (date("Y-m-d", filemtime($logfilename)) !== date('Y-m-d')) {
$fileDate = date("Y-m-d", filemtime($logfilename));
$newName = $logpath .'/'.$filename. "_" . $fileDate.'.'.$extention;
if (file_exists($logfilename)) {
rename($logfilename, $newName);
}
}
}
}
I have an application that has upload Excel file process. Then PHPExcel will process the uploaded Excel file.
This is the flow of process:
Upload file
Save file into local directory
Get file from local dir
Read the file using PHPExcel
I've successfully save the Excel file to local directory, reading and get the data from the Excel file.
But when I use an Excel file that contain 90K of rows x 25 columns, that file didn't saved into local directory. Then I'm trying to print_r the data and it return error=> 1
This is the print_r result
1. Excel with less than 8k rows and successfully saved to local dir:
2. Excel with 90K of rows and didn't saved into local dir:
This is my code in controller
public function actionCreate() {
$connection = \Yii::$app->db;
$model = new MasterProduct();
$userId = Yii::$app->user->id;
$date = new DateTime('now', new \DateTimeZone('Asia/Bali'));
$created_at = $date->format('Y:m:d H:i:s');
$dirTrash = Yii::getAlias('#webroot/trash');
$dirSubTrash = Yii::getAlias('#webroot/trash/trash_app');
//create directory in local if doesn't exist
if (!is_dir($dirTrash)) {
mkdir(Yii::getAlias('#webroot/trash'));
if (!is_dir($dirSubTrash)) {
mkdir(Yii::getAlias('#webroot/trash/trash_app'));
}
} else {
if (!is_dir($dirSubTrash)) {
mkdir(Yii::getAlias('#webroot/trash/trash_app'));
}
}
if (Yii::$app->request->post()) {
Yii::$app->response->format = Response::FORMAT_JSON;
$result = [];
$fileMaster = UploadedFile::getInstancesByName('master_product');
$middleName = substr(md5(microtime() * 100000), rand(0, 9), 5);
//named the uploaded file, then save into local directory
if ($fileMaster !== null) {
$nameMaster = $userId . '_MP' . '_' . $middleName . '_' . date('Y-m-d') . '_' . $fileMaster[0]->getBaseName() . "." . $fileMaster[0]->getExtension();
$pathMaster = Yii::getAlias('#webroot/trash/trash_app/') . $nameMaster;
$fileMaster[0]->saveAs($pathMaster);
} else {
$error[] = "Choose the" . "<strong>" . " Excel " . "</strong>" . "file first.";
$result = [
'error' => $error
];
}
//this the code i've used to print_out the array in above images
echo '<pre>';
print_r($fileMaster);
die();
//Access, and get the data from local directory
$objPHPExcelMaster = new \PHPExcel();
$fileNameMaster = Yii::getAlias('#webroot/trash/trash_app/') . $nameMaster;
$inputFilesMaster = fopen(Yii::getAlias('#webroot/trash/trash_app/') . $nameMaster, "r");
try {
$inputFileTypeMaster = \PHPExcel_IOFactory::identify($fileNameMaster);
$objReaderMaster = \PHPExcel_IOFactory::createReader($inputFileTypeMaster);
$objPHPExcelMaster = $objReaderMaster->load($fileNameMaster);
} catch (Exception $ex) {
die('Error');
}
$sheetMaster = $objPHPExcelMaster->getSheet(0);
$highestRowMaster = $sheetMaster->getHighestDataRow();
$highestColumnMaster = $sheetMaster->getHighestDataColumn();
//read the Excel file and set into array
for ($row = 1; $row <= $highestRowMaster; ++$row) {
$rowDataMaster = $sheetMaster->rangeToArray('A' . $row . ':' . $highestColumnMaster . $row, NULL, TRUE, NULL);
}
$tempDataMaster = mysql_escape_string(json_encode($rowDataMaster));
$commandCheckExist = "SELECT COUNT(user_id) FROM `gm_json_master` WHERE id=$userId";
$queryCheckExist = Yii::$app->db->createCommand($commandCheckExist)->execute();
//save data into db
if ($queryCheckExist == 0) {
$command_2 = "INSERT INTO json_master(json_m_product) VALUES('$tempDataMaster')";
$query_2 = Yii::$app->db->createCommand($command_2)->execute();
} else {
$commandUpdate = "UPDATE json_master SET json_m_product='$tempDataMaster'";
$queryUpdate = Yii::$app->db->createCommand($commandUpdate)->execute();
}
$result = [
'url' => Url::to(['/gm/json-master-product/save'])
];
return $result;
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
How does this happen? and how do I can read big data of Excel using PHPExcel?
An error code of 1 means that the file size exceeds the max filesize allowed by your server's configuration.
From the docs:
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
I would try upping that limit as well as the max POST size limit and see if that helps.
i have an issue with uploading multiple files to disk. here is my code.
i have a request with 2 pictures that gets sent to a upload function. the 2 pictures are in a var called $multiUpload
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$file = array();
$filename = array();
foreach($multiUpload as $key=>$val){
// get the file extension
$file[] = explode('.',$val);
// create custom file name
$filename[] = time().'.'.$file[$key][1];
//send to the upload function
$this->uploadToDisk($folderPath, $filename[$key]);
// sleep 1 sec so that the pic names will be different
sleep(1);
}
return $filename;
}
public function uploadToDisk($folderPath, $filename)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->setDestination($folderPath);
$adapter->addFilter( 'Rename',array(
'target' => $folderPath."/".$filename,
'overwrite' => true
) );
if ($adapter->receive()) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
this will return
Array
(
[0] => Array
(
[0] => 1332977938.jpg
[1] => 1332977939.jpg
)
)
but only array[0][0] or 1332977938.jpg will actually get saves to the disk.
Why are they now both get saved? wired
any ideas?
I suspect the second call to uploadToDisk is returning fail because you can only call Zend_File_Transfer_Adapter_Http::receive() once for each file. Since you are not specifying a file when calling receive, it is receiving all of the files the first time you call uploadToDisk and subsequently is failing with a File Upload Attack error.
Here is some code you can try. This tries to receive each file individually and then save them one at a time with each call to uploadToDisk.
A few notes about the code:
The first parameter to uploadToDisk ($val) may need to be changed as I am not sure what the original values are. It should correspond to one of the element names used for the file upload (See Zend_File_Transfer_Adapter_Http::getFileInfo()) for a list of the files.
I changed the method for generating a unique filename so you don't have to sleep(1)
Zend_File_Transfer_Adapter_Abstract::setDestination() is deprecated and will go away in the future. Instead, just use the Rename filter. When using Rename, setDestination() has no effect.
And here it is...
<?php
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$filenames = array();
foreach($multiUpload as $key => $val){
// get the file extension
$ext = explode('.', $val);
$ext = $ext[sizeof($ext) - 1];
// create custom file name
do {
$filename = uniqid(time()) . '.' . $ext;
$diskPath = $folderPath . $filename;
} while (file_exists($diskPath));
$filenames[$key] = $filename;
//send to the upload function
// $val is the file to receive, $diskPath is where it will be moved to
$this->uploadToDisk($val, $diskPath);
}
return $filename;
}
public function uploadToDisk($file, $filename)
{
// create the transfer adapter
// note that setDestination is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($file)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}