In my UsersController.php
public function uploadFile()
{
$filename = '';
if ($this->request->is('post')) {
$uploadData = $this->data['uploadFile']['image'];
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) {
return false;
}
$filename = basename($uploadData['name']);
if ($this->User->save($filename)) {
$this->Session->setFlash(__('Your imagename has been saved.'));
}
$uploadFolder = WWW_ROOT. 'files';
$filename = time() .'_'. $filename;
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder);
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
//$this->set('pdf_path', $fileName);
return false;
}
}
}
}
And in my uploadfile.ctp
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
echo $this->Form->input('image', array('type' => 'file','label' => 'Pdf'));
echo $this->Form->end('Upload file');
?>
In my db I have table name "image" along with some other fields. Now I'm not able to upload file name into db.
If you have a table name called 'image', then it should be related to the user model. $this->User->save($filename) needs at least a table field called 'filename' in the User table AND it needs to be assigned to a user via $this->User->id = $user_id;
If your image table has an image model which is related to the user model, read the book's chapter 'Saving related model data' http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto
Related
I am not able to save the photo name and photo dir in the users table based on logged in used id.I am trying to upload the user photo for the existing user based on his used id.The photo fields are not getting updated for the existing user. I am trying to upload the photo using this plugin josegonzalez. Please help me.
<?php echo $this->Form->create($user, ['type' => 'file']); ?>
<?php echo $this->Form->input('photo',['type' => 'file', 'class' => 'form-control']); ?>
<?php echo $this->Form->input('photo_dir', ['type' => 'hidden']); ?>
<?php echo $this->Form->button(__('Submit'), ['type'=>'submit','class' => 'btn btn-success']); ?>
<?php echo $this->Form->end(); ?>
UsersTable
$this->addBehavior('Josegonzalez/Upload.Upload', [
'photo' => [
'fields' => [
// if these fields or their defaults exist
// the values will be set.
'dir' => 'photo_dir', // defaults to `dir`
],
],
]);
UsersController/add
public function add($id=null)
{
if ($this->request->is('post')) {
if (!$id) {
$id = $this->Auth->user('id');
}
$user = $this->Users->get($id);
$fileName = $this->request->data['photo']['name'];
$user->photo = $fileName;
//$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('Your photo has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your photo.'));
}
$this->set('user', $user);
}
Have you tried using 'enctype' in your form tag?
<form enctype="multipart/form-data">
It is explained here.
You can use Proffer plugin. It is easy to use and can be used to generate thumbnails too. I'm using it since 3.1 and working fine. It's even working on 3.3
https://github.com/davidyell/CakePHP3-Proffer
This is how it worked. I did not use any plugin. I uploaded single image at a time.
UsersController/add function.
public function add()
{
//check for logged in user authentication
$id = $this->Auth->user('id');
$user = '';
//check if the request is post
if ($this->request->is('post')) {
$user = $this->Users->get($id);
//check if upload file is not empty
if(!empty($this->request->data['photo']['name'])){
$fileName = $this->request->data['photo']['name'];
$extention = pathinfo($fileName,PATHINFO_EXTENSION);
$arr_ext = array('jpg', 'jpeg', 'gif','png');
//check for uploded file extension
if(in_array($extention, $arr_ext)){
$newfileName=$id.'.'.$extention;
$destDir = WWW_ROOT .'img'. DS .'users'. DS . $newfileName;
//move uploded file to destination
if(move_uploaded_file($this->request->data['photo']['tmp_name'],$destDir)){
$user->photo = $newfileName;
//save the uploded image in user table
if ($this->Users->save($user)) {
$this->Flash->success(__('Your profile photo has been uploaded successfully.'));
return $this->redirect([
'controller' => 'Users',
'action' => 'view', $id
]);
} else{
$this->Flash->error(__('Unable to upload image, please try again.'));
}
}else{
$this->Flash->error(__('Unable to upload image, please try again.'));
}
}else{
$this->Flash->error(__('Please choose a image to upload.'));
}
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
$this->set('id', $id);
}
I have csv file. and i have already uploaded now i want put its data into my database in cakephp 2.7.5
csv file contain field name exactly same as employee table field name
my question is how to put data in employee table
here function code
public function import_csv(){
$this->loadModel('Csvimport');
if ($this->request->is('post', 'put')) {
$this->request->data['Csvimport']['created_user_id'] = $this->Auth->user('id');
$this->request->data['Csvimport']['modified_user_id'] = $this->Auth->user('id');
if (!empty($this->request->data)) {
$file = $this->request->data['Csvimport']['file_name'];
$name = explode(".", $file['name']);
//echo "before:".$file['name'][$i];
$name = uniqid().".".$name[1];
//echo "after:".$name;
$ext = substr(strtolower(strrchr($name, '.')), 1); //get the extension
$arr_ext = array('csv'); //set allowed extensions
//only process if the extension is valid
if ($file['size'] < 1000000) {
if(in_array($ext, $arr_ext)){
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/attachments/csvimports/' . $name);
//prepare the filename for database entry
$this->request->data['Csvimport']['file_name'] = $name;
$this->request->data['Csvimport']['file_type'] = $file['type'];
$this->request->data['Csvimport']['file_size'] = $file['size'];
}else{
$message = 'Your File should be in given formats only.';
$this->set('message',$message);
$this->Session->setFlash($message, 'error_flesh', array(), 'error');
$this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv'));
}
}else{
$message = 'Your File should be Upto 1MB only.';
$this->set('message',$message);
$this->Session->setFlash($message, 'error_flesh', array(), 'error');
$this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv'));
}
}
$this->Csvimport->id = $id;
if ($this->Csvimport->save($this->request->data)){
$message = 'The Csv File has been Uploaded';
$this->set('message',$message);
$this->Session->setFlash($message, 'success_flesh', array(), 'successfully');
$this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv'));
} else {
$message = 'The Csv File could not be Uploaded. Please, try again.';
$this->set('message',$message);
$this->Session->setFlash($message, 'error_flesh', array(), 'error');
}
}
}
If you need to loop over every row of data before importing it,
consider using
$this->Csvimport->create()
$this->Csvimport->save(['fieldName'=>$data1, 'fieldName'=>$data2, ... ]);
If you don't need that, then use saveAll on the whole array once you have it as such.
here is cakes documentation:
http://book.cakephp.org/2.0/en/models/saving-your-data.html
I have a view that is add a called help desk opening form (referring to add function, of course), and have this function is to upload that file to attach request, which is connected with a component, but I do not want to Let them in different view, because if I just send a file upload through the view, the image is "lost " and does not turn the call. I need within the add function I can call the upload function, to join views. If I call her by $ this-> upload (); Or simply make all the checking in of add, does not find the component, returning me an error (which I put down ), I believe the conflict is in the request-> data but do not know if there is a way to join the way I explained.
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is(['post', 'put'])) {
$this->Posts->patchEntity($post, $this->request->data);
$post->user_id = $this->Auth->user('id');
if ($this->Posts->save($post)) {
$this->Flash->success(__('send'));
return $this->redirect(['action' => 'listar']);
}
$this->Flash->error(__('not send'));
}
$this->set(compact('post'));
}
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data(['uploadfile']));
return $this->redirect(['action'=>'add']);
}
}
Component:
public function send( $data )
{
if ( !empty( $data) ) {
if ( count( $data) > $this->max_files ) {
throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
}
foreach ($data as $file) {
$filename = $file['name']; //line 32
$file_tmp_name = $file['tmp_name']; //33
$dir = WWW_ROOT.'img'.DS.'Anexos';
$allowed = array('png', 'jpg', 'jpeg');
if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) ) {
throw new InternalErrorException("Error Processing Request.", 1);
}elseif( is_uploaded_file( $file_tmp_name ) ){
$filename = Text::uuid().'-'.$filename;
$filedb = TableRegistry::get('Arquivos');
$entity = $filedb->newEntity();
$entity->filename = $filename;
$filedb->save($entity);
move_uploaded_file($file_tmp_name, $dir.DS.$filename);
}
}
}
}
Error when calling upload();
Warning (2): Illegal string offset 'name' [APP/Controller\Component\UploadComponent.php, line 32]
Warning (2): Illegal string offset 'tmp_name' [APP/Controller\Component\UploadComponent.php, line 33]
view:
<?php
//this is my view add ;
echo $this->Form->input('id' );
echo $this->Form->input('titulo');
echo $this->Form->input('ip');
echo $this->Form->input('mensagem');
?>
//and this is my view upload, I would like to join with add ;
<?php echo $this->Form->create(null, ['type' => 'file']); ?>
<label>Arquivos</label>
<?php
echo $this->Form->file('uploadfile.', ['multiple']);
echo $this->Form->button('Anexar', ['action' => 'submit']);
echo $this->Form->end();
?>
You aren't accessing uploadfile array. This line $this->Upload->send($this->request->data(['uploadfile'])); should be like $this->Upload->send($this->request->data('uploadfile'));.
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data('uploadfile'));
return $this->redirect(['action'=>'add']);
}
}
I am trying to create a file upload on cakephp, I haven't been able to find any decent tutorials for cakephp 3.0 that go in detail, and I don't understand how to install plugins.
I have this in my add section
echo $this->Form->create('filename', array('action' => 'upload', 'type' => 'file'));
echo $this->Form->file('filename');
I haven't added anything in the controller yet
/**
* Index method
*
* #return void
*/
public function index()
{
$this->paginate = [
'contain' => ['Courses']
];
$this->set('contents', $this->paginate($this->Contents));
$this->set('_serialize', ['contents']);
}
/**
* View method
*
* #param string|null $id Content id.
* #return void
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$content = $this->Contents->get($id, [
'contain' => ['Courses']
]);
$this->set('content', $content);
$this->set('_serialize', ['content']);
}
/**
* Add method
*
* #return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$content = $this->Contents->newEntity();
if ($this->request->is('post')) {
$content = $this->Contents->patchEntity($content, $this->request->data);
if ($this->Contents->save($content)) {
$this->Flash->success('The content has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The content could not be saved. Please, try again.');
}
}
$courses = $this->Contents->Courses->find('list', ['limit' => 200]);
$this->set(compact('content', 'courses'));
$this->set('_serialize', ['content']);
}
/**
* Edit method
*
* #param string|null $id Content id.
* #return void Redirects on successful edit, renders view otherwise.
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$content = $this->Contents->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$content = $this->Contents->patchEntity($content, $this->request->data);
if ($this->Contents->save($content)) {
$this->Flash->success('The content has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The content could not be saved. Please, try again.');
}
}
$courses = $this->Contents->Courses->find('list', ['limit' => 200]);
$this->set(compact('content', 'courses'));
$this->set('_serialize', ['content']);
}
/**
* Delete method
*
* #param string|null $id Content id.
* #return void Redirects to index.
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$content = $this->Contents->get($id);
if ($this->Contents->delete($content)) {
$this->Flash->success('The content has been deleted.');
} else {
$this->Flash->error('The content could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
but after this no idea what to do.
First of all, you need to decide on WHEN you're going to handle uploads. I've managed to create a dirty (but working) approach using beforeMarshal method and afterSave method (I'll explain why these two at the end).
If you create your file input like:
<?= $this->Form->file('submittedfile', ['class' => 'form-control input-upload', 'style' => 'height:100px']) ?>
or for hasMany association:
<?= $this->Form->file('images.'.$i.'.submittedfile', ['class' => 'form-control input-upload', 'style' => 'height:100px']) ?>
and you define the right associations:
$this->hasMany('Images', [
'foreignKey' => 'model_id'
]);
you could process those files before the Entity gets patched and saved:
public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options) {
$images = array();
$dir = md5(time().$data['name']);
for ($i = 0; $i < count($data['images']); $i++) {
$image = $data['images'][$i]['submittedfile'];
if (!empty($image['name'])) {
if(!isset($data['id'])) {
$data['temp_dir'] = $dir;
}
else {
$dir = $data['id'];
}
if ($this->Images->uploadFile(array('img', 'model', $dir), $image) === true) {
$images[] = array('name' => pathinfo($image['name'], PATHINFO_FILENAME), 'ext' => pathinfo($image['name'], PATHINFO_EXTENSION));
}
}
}
$data['images'] = $images;
}
This is of course an example. I've decided to check, if there's an ID property set on the Entity (like for edit), because if it's not (like for create), you have to somehow identify the right path.
Here you've got a file uploading function:
public function uploadDir($path = array()) {
return $this->wwwRoot . implode(DS, $path);
}
public function uploadFile($path = array(), $filetoupload = null) {
if (!$filetoupload) {
return false;
}
$dir = new Folder($this->uploadDir($path), true, 755);
$tmp_file = new File($filetoupload['tmp_name']);
if (!$tmp_file->exists()) {
return false;
}
$file = new File($dir->path . DS . $filetoupload['name']);
if (!$tmp_file->copy($dir->pwd() . DS . $filetoupload['name'])) {
return false;
}
$file->close();
$tmp_file->delete();
return true;
}
If you added your images while there was no subdirectory with main entity ID, you have to rename the directory as soon as you get the ID:
public function afterSave(Event $event, Entity $entity, \ArrayObject $options) {
if(!empty($entity->temp_dir)) {
$this->Images->renameFolder(array('img', 'model', $entity->temp_dir),$entity->id);
}
}
calling:
public function renameFolder($path = array(), $newName) {
$oldPath = $this->wwwRoot . implode(DS, $path);
$nameToChange = array_pop($path);
array_push($path, $newName);
$newPath = $this->wwwRoot . implode(DS, $path);
return rename($oldPath, $newPath);
}
Using beforeMarshal you're able to inject your file data into Entity structure before the whole Entity is ready for saving (with associations).
Using afterSave you're able to identify the main object ID and call the set of objects you've uploaded before.
Remember to set recursive rights for saving files onto the directory, as well as rights for creating and renaming directories.
i was trying to upload image using cakephp , i got the following error :
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]
<?php echo $this->Form->create('User',array('type'=>'file'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
anything wrong with what i've did ?
You study cakephp manual properly HOW form type can be File ?????? :)
Use this
<?php echo $this->Form->create('User',array('enctype'=>'multipart/form-data'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
You need to treat the file upload in the controller. If you debug the request you'll see that profile_pic field is an array:
# in controller:
if ($this->request->is('post')) {
debug($this->request->data); die();
}
# result:
array(
'User' => array(
'profile_pic' => array(
'name' => 'wappy500x500.jpg',
'type' => 'image/jpeg',
'tmp_name' => '/tmp/phptk28hE',
'error' => (int) 0,
'size' => (int) 238264
)
)
)
Short answer:
public function upload() {
if ($this->request->is('post')) {
if(isset($this->request->data['User']['profile_pic']['error']) && $this->request->data['User']['profile_pic']['error'] === 0) {
$source = $this->request->data['User']['profile_pic']['tmp_name']; // Source
$dest = ROOT . DS . 'app' . DS . 'webroot' . DS . 'uploads' . DS; // Destination
move_uploaded_file($source, $dest.'your-file-name.jpg'); // Move from source to destination (you need write permissions in that dir)
$this->request->data['User']['profile_pic'] = 'your-file-name.jpg'; // Replace the array with a string in order to save it in the DB
$this->User->create(); // We have a new entry
$this->User->save($this->request->data); // Save the request
$this->Session->setFlash(__('The user has been saved.')); // Send a success flash message
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
Of course you need to make extra validations on the uploaded file.
Further reading: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+cakephp+upload+file