I'm trying to import CSV file to the database using yii2 framework.
Controller
public function actionIndex($message=””)
{
// $model = new ProjectDocument;
//error_reporting(E_ALL);
//ini_set('display_error', 1);
$model = new ProjectDocument();
if ($model->load(Yii::$app->request->post()) ) {
$model->file = UploadedFile::getInstance($model, 'file');
// if ($model->load(Yii::$app->request->post())){
// $filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$title = _file[1];
$description = $file[2];
$phase = $file[3];
$modelnew->title = $title;
$modelnew->description = $description;
$modelnew->phase = $phase;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->render('create',array('model'=>$model, 'message'=>$message));
}
}else{
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
But I getting an error like this,
"Access to undeclared static property: Yii::$app"
Anyone can help me to rectify the error, Thank you in advance..
Related
I started working on Zend Framework image upload.The code is not showing any errors but image not moving to proper destination.
public function uploadAction()
{
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form = new UploadForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload'); //upload destination
$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if($favadapter->receive($favicon))
{
echo "suceess";
}
else
{
echo "Failed";
}
die;
}
}
return array('form' => $form);
}
The image is not received and gives failed message.Can you solve this problem.Thanks in advance
You write "gives failed message" so apparently something goes wrong. You should try to find out what and why... All we can do is guess with the information you are giving inside your question.
If you read the ZF2 documentation on this file adapter class here then you can see that the adaper has a getMessages method. This might give you some insight on what actually goes wrong:
$adapter = new Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
This code snippet comes straight out of the official docs!
Your final running code make sure you comment filters
public function uploadAction()
{
error_reporting(0);
$em = $this->getEntityManager();
$form = new UploadForm($em);
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload/'); //upload destination
//$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if (!$favadapter->receive())
{
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
else
{
echo "success";
}
// die;
}
}
// if ($request->isPost())
// {
// $fname = $_FILES['fileupload']['name'];
// $tmp_name = $_FILES["fileupload"]["tmp_name"];
// $uploads_dir = 'public/img/upload';
// if(move_uploaded_file($tmp_name,"$uploads_dir/$fname"))
// {
// echo "Uploaded";
// }
// else
// {
// echo "Error";
// }
// }
return array('form' => $form);
}
I need to UPDATE record with out changing or deleting filename(i mean file) , OR reinsert file again so how i can do this?
here is my actionCreate, How i can write update?
public function actionCreate() {
$model = new Page;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save()) {
if ($model->filename !== null) {
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
So Please can anyone find a solution
If you don't need to change or delete filename in edit/update then ignore filename (and upload part) assuming the file is alrready uploaded and you don't wish to change/delete it.
public function actionUpdate($id) {
$model = $this->loadModel($id);
$file = $model->filename;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = $file;
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
Try this, it's working for me -
create a upload folder outside protected directory and also give read/write permission.
actionCreate function -
public function actionCreate() {
$model = new Page();
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if(!empty( $fileName)){
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias('application') . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
if(!$model->hasErrors() && $model->validate() && $model->save(false)) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'success'));
}
}
}
actionUpdate function -
public function actionUpdate() {
$model = Page::model()->findbyPK($id);
$model->scenario = 'update';
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
if(empty($_POST['Page']['filename'])) { $file_name = $model->filename; } //store existing file name into a variable if your uploading a file on update
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if($model->validate()) {
if(!empty($fileName)) {
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias( 'application' ) . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
else {
$model->filename = $file_name; //allow existing file name
}
if( !$model->hasErrors() && $model->save(false) ) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'update'));
}
}
}
In model rules array define this -
array('filename', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')
I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!
I would like to get object by id from database inside Controller then use its name to create directory with that name.
public function album($id = null) {
$dirname = $this->Dog->query('SELECT * from dogs WHERE id='$id'');
$dir = new Folder(WWW_ROOT . 'albums' . DS . 'files' . DS . $dirname->name , true, 0755);
$this->layout = 'edit';
if (!$id) {
throw new NotFoundException(__('Zły post'));
}
$Dog = $this->Dog->findById($id);
if (!$Dog) {
throw new NotFoundException(__('Zły post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Dog->id = $id;
if ($this->Dog->save($this->request->data)) {
$this->Session->setFlash(__('Edycja zakończona sukcesem.'));
$this->redirect(array('action' => 'index_psy'));
} else {
$this->Session->setFlash(__('Spróbuj ponownie.'));
}
}
}
I have tried a few other solutions but none of them seems to work.
Thanks for help
public function album($id) {
//if id doesn't exist Exit
if (!$this->Dog->exists($id)) {
throw new NotFoundException(__('Invalid album'));
}
$dog = $this->Dog->findById($id);
//create a folder with directory name
$path = 'files' . DS . $dog['Dog']['name'];
$folder = new Folder($path , true, 0755);
$this->layout = 'edit';
}
}
look at here just to get an idea
I have conroller baner, and when I try to run it (run upload function http://localhost/010/baner/upload_img), I got 404 error:
The page you requested was not found
What is wrong here?
The controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload_Baner extends CI_Controller {
protected $path_img_upload_folder;
protected $path_img_thumb_upload_folder;
protected $path_url_img_upload_folder;
protected $path_url_img_thumb_upload_folder;
protected $delete_img_url;
function __construct() {
parent::__construct();
$this->setPath_img_upload_folder("public/img/promotions/");
$this->setPath_img_thumb_upload_folder("public/img/promotions/thumbnails/");
$this->setDelete_img_url(base_url() . 'upload_baner/deleteImage/');
$this->setPath_url_img_upload_folder(base_url() . "public/img/promotions/");
$this->setPath_url_img_thumb_upload_folder(base_url() . "public/img/promotions/thumbnails/");
}
public function upload_img() {
//Format the name
$name = $_FILES['userfile']['name'];
$name = strtr($name, 'ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃà áâãäåçèéêëìÃîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
// replace characters other than letters, numbers and . by _
$name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);
//Your upload directory, see CI user guide
$config['upload_path'] = $this->getPath_img_upload_folder();
$config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
$config['max_size'] = '1000';
$config['file_name'] = $name;
//Load the upload library
$this->load->library('upload', $config);
if ($this->do_upload()) {
//If you want to resize
$config['new_image'] = $this->getPath_img_thumb_upload_folder();
$config['image_library'] = 'gd2';
$config['source_image'] = $this->getPath_img_upload_folder() . $name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 193;
$config['height'] = 94;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = $this->upload->data();
//Get info
$info = new stdClass();
$info->name = $name;
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $this->getPath_img_upload_folder() . $name;
$info->thumbnail_url = $this->getPath_img_thumb_upload_folder() . $name; //I set this to original file since I did not create thumbs. change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$name
$info->delete_url = $this->getDelete_img_url() . $name;
$info->delete_type = 'DELETE';
//Return JSON data
if (IS_AJAX) { //this is why we put this in the constants to pass only json data
echo json_encode(array($info));
//this has to be the only the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
} else { // so that this will still work if javascript is not enabled
$file_data['upload_data'] = $this->upload->data();
echo json_encode(array($info));
}
} else {
// the display_errors() function wraps error messages in <p> by default and these html chars don't parse in
// default view on the forum so either set them to blank, or decide how you want them to display. null is passed.
$error = array('error' => $this->upload->display_errors('',''));
echo json_encode(array($error));
}
}
public function do_upload() {
if (!$this->upload->do_upload()) {
return false;
} else {
//$data = array('upload_data' => $this->upload->data());
return true;
}
}
//Function Delete image
public function deleteImage() {
//Get the name in the url
$file = $this->uri->segment(3);
$success = unlink($this->getPath_img_upload_folder() . $file);
$success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);
//info to see if it is doing what it is supposed to
$info = new stdClass();
$info->sucess = $success;
$info->path = $this->getPath_url_img_upload_folder() . $file;
$info->file = is_file($this->getPath_img_upload_folder() . $file);
if (IS_AJAX) {//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
} else { //here you will need to decide what you want to show for a successful delete
var_dump($file);
}
}
public function get_files() {
$this->get_scan_files();
}
public function get_scan_files() {
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
protected function get_file_object($file_name) {
$file_path = $this->getPath_img_upload_folder() . $file_name;
if (is_file($file_path) && $file_name[0] !== '.') {
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
$file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
//File name in the url to delete
$file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
protected function get_file_objects() {
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
)));
}
public function getPath_img_upload_folder() {
return $this->path_img_upload_folder;
}
public function setPath_img_upload_folder($path_img_upload_folder) {
$this->path_img_upload_folder = $path_img_upload_folder;
}
public function getPath_img_thumb_upload_folder() {
return $this->path_img_thumb_upload_folder;
}
public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder) {
$this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
}
public function getPath_url_img_upload_folder() {
return $this->path_url_img_upload_folder;
}
public function setPath_url_img_upload_folder($path_url_img_upload_folder) {
$this->path_url_img_upload_folder = $path_url_img_upload_folder;
}
public function getPath_url_img_thumb_upload_folder() {
return $this->path_url_img_thumb_upload_folder;
}
public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder) {
$this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
}
public function getDelete_img_url() {
return $this->delete_img_url;
}
public function setDelete_img_url($delete_img_url) {
$this->delete_img_url = $delete_img_url;
}
}
Your controller is named Upload_Baner so unless you have a route defined that maps baner to upload_Baner this won't work. Does this url work?:
http://localhost/010/upload_Baner/upload_img
That is what your current controller will map to without the route.