Uploading a file in your application can be used to upload an image or documents.
With the help of the cakephp html we can create a form with the input field of type file which allows to browse and select the file from your systems.
lets create a cakephp html form for the same ,
<center>
<div class="users view">
<h2><?php echo('User'); ?></h2>
<?php
echo $this->Form->create('uploadFile', array('type' => 'file')); //input field of type file allows browse your file.
echo $this->Form->input('pdf_path', array('type' => 'file','label' => 'Pdf'));
echo $this->Form->end('Upload file');
$image_src = $this->webroot.'img/'.$image;
?>
<img src="<?php echo $image_src;?>">
</div>
</center>
In the controller create a function that performs the overall task of uploading the file ,
public function upload_file() {
$filename = '';
$uploadData = $this->data['upload_File']['pdf_path'];
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) {
return false;
}
$filename = basename($uploadData['name']);
$uploadFolder = WWW_ROOT. 'img';
$filename = time() .'_'. $filename;
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder);
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
}
$this->set('image',$file_name1);
}
In the above code of the controller the statement $uploadData = $this->data['upload_File']['pdf_path']; will fetch the uploaded file path from the form filed of type file and assign it to the $uploadData. same way the below statements dose for file name webroot path etc..
$filename = basename($uploadData['name']); this statement will fetch the file name and assign it to the $filename.
$uploadFolder = WWW_ROOT. 'img'; this statement will set the webroot path with the folder name where the file is to be uploaded.
$filename = time() .'_'. $filename; this statement append the random no before the file name so that it wont get conflict from already existing file with the same name, it protects from re-writing the file.
$uploadPath = $uploadFolder . DS . $filename; Finally this statement will save the whole path where the file to be uploaded with the new file name.
finally the key statement move_uploaded_file($uploadData['tmp_name'], $uploadPath) have the function move_uploaded_file() which takes the two statements first one is the temp file path and second one is the original file name and then uploads the file on the original location.
0 Comment(s)