I want to know how to get a value of object. I am using Yii framework for imeplement a download function. How to pass a parameter from frontend
I printed out a object, but I don't know how to get a value from this object.
Array
(
[file] => CUploadedFile Object
(
[_name:CUploadedFile:private] => 23602414.pdf
[_tempName:CUploadedFile:private] => D:\wamp\tmp\php8780.tmp
[_type:CUploadedFile:private] => application/pdf
[_size:CUploadedFile:private] => 181004
[_error:CUploadedFile:private] => 0
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
[layout] => //layouts/column1
[menu] => Array
(
)
[breadcrumbs] => Array
(
)
[defaultAction] => index
[_widgetStack] => Array
(
)
)
I want to get the "23602414.pdf", and store it to a varable.
This is my code.
<?php $model=new Upload(); ?>
<?php if(isset($_POST['Upload'])){$model->attributes=$_POST['Upload'];
$this->file=CUploadedFile::getInstance($model,'file');
}?>
<?php echo CHtml::link('Download file',array('/upload/download','id'=>'23602414.pdf')); ?>
Instead of hard code as 'id'=>'23602414.pdf', I want to echo the file name in there.
try this
<?php $model=new Upload(); ?>
<?php if(isset($_POST['Upload'])){$model->attributes=$_POST['Upload'];
$this->file=CUploadedFile::getInstance($model,'file');
}?>
<?php echo CHtml::link('Download file',array('/upload/download','id'=>$this->file->getName())); ?>
Documentation here https://www.yiiframework.com/doc/api/1.1/CUploadedFile
I rewrited my code like below:
My model:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return array(
array('file', 'file', 'types'=>'pdf'),
);
}
public function downloadFile($fullpath){
$dir = Yii::getPathOfAlias('application.uploads');
$filename= $fullpath;
if(!empty($fullpath)){
$file = $dir."\\"."$filename";
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=$filename");
#readfile($file);
Yii::app()->end();
}
else {return false;}
}
}
My controller:
<?php
class UploadController extends Controller
{
public $file;
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$this->file=CUploadedFile::getInstance($model,'file');
$file=$this->file;
if($model->validate()){
$uploaded = $file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}
public function actionDownload($id){
$path = Yii::getPathOfAlias('/yiiroot/trackstar/protected/uploads/')."$id";
$upload=new Upload();
$upload->downloadFile($path);
}
}
My view:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array
('enctype'=>'multipart/form-data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, 'file')?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
<br/>
<?php $model=new Upload(); ?>
<?php if(isset($_POST['Upload'])){$model->attributes=$_POST['Upload'];
$this->file=CUploadedFile::getInstance($model,'file');
echo CHtml::link('Download file',array('/upload/download','id'=>$this->file->getName()));
}?>
refer:PHP getName() Function
Related
Hi im trying to upload an image but the image is not getting uploaded to the folder.
and i don´t get any error message is there anyone that have a solution to this i followed the documentation on https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
Controller
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = Uploadedfile::getInstance($model, 'imagefile');
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
Model
public $imageFile;
public $hight;
public $width;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, gif'],
];
}
public function upload()
{
if ($this->validate()) {
$path = $this->uploadPath() . $this->imageFile->namespace . '.' . $this->imageFile->extension;
$this->imageFile->saveAs($path);
$this->image = $this->imageFile->basename . '.' . $this->imageFile->extension;
return true;
} else {
return false;
}
}
public function uploadPath(){
return 'basic/web/uploads/';
}
View
<div class="col-lg-4">
<h2>Heading</h2>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Resize</button>
<?php ActiveForm::end() ?>
</div>
I think file was not saved to basic/web/uploads folder, please do according to ex, $this->imageFile->saveAs('uploads/' ...
Also try create folder 'uploads' in web/, after this check permissions to the folder
Here is my code
View (edit.ctp):
<?php echo $this->Form->create('Answer'); ?>
<?php echo $this->Form->input('Answer.0.value', array('class' => 'validate', 'type' => 'text', 'id' => 'Answer.0.id', 'label' => false)) ?>
<?php echo $this->Form->end('Edit Answer'); ?>
Controller:
public function edit($id) {
$this->layout = 'request_processing_edit';
$data = $this->Response->findById($id);
if ($this->request->is(array('post', 'put'))) {
$this->Response->id = $id;
if ($this->Answer->save($this->request->data)) {
$this->Session->setFlash('Answer Editted');
$this->redirect('index');
}
}
This is how $this->request->data array looks like:
I need the id to be in the same array as value upon clicking submit in the view
Is there any way to achieve this without having to build the array in the controller? Looking for a way to have both id and value passed in the request upon clicking submit from the view/form.
So, Here you can use this way
In your Controller :
$data = $this->Post->findById($id);
if ($this->request->is(array('post', 'put'))) {
$this->Answer->id = $id;
if ($this->Answer->save($this->request->data)) {
$this->Session->setFlash('Answer Editted');
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('Answer Not Editted');
}
if (!$this->request->data) {
$this->request->data = $data;
In Your View File Pass Hidden Field ID :
echo $this->Form->input('id', array('type' => 'hidden'));
Found a solution by adding this line of code in my ctp file:
<?php echo $this->Form->input('Answer.0.id', array('hidden' => true)) ?>
My view:
<?php
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?= $form->field($model, 'document_file')->fileInput()->label(Yii::t('app', 'Attachment')) ?>
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
My model:
class Documents extends \yii\db\ActiveRecord
{
public $document_file;
public function rules()
{
return [
[['document_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, xls'],
];
}
}
My controller:
$model = new Documents();
if($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->document_file = UploadedFile::getInstance($model, 'document_file');
$model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
} else {
print_r($model->getErrors());
}
return $this->render('new', compact('model'));
This code is supposed to upload file to server. But I get the error from print_r - it says
Array ( [document_file] => Array ( [0] => Upload a file. ) )
What am I doing wrong and how to upload a file to server???
File attributes (document_file in your example) could not be assigned via load(), so the value of the following expression is false:
$model->load(Yii::$app->request->post()) && $model->validate()
That is why you got the print error message. You should use UploadedFile::getInstance() to assign the document_file attribute before validate():
$model = new Documents();
if(Yii::$app->request->isPost) {
$model->document_file = UploadedFile::getInstance($model, 'document_file');
if ($model->validate()) {
$model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
} else {
print_r($model->getErrors());
}
}
return $this->render('new', compact('model'));
my problem is with two or more files.
this codes is form Yii application development cookbook(2nd edition), chapter 4
i use Yii 1.1.14
controller:
<?php
class UploadController extends Controller
{
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$files=CUploadedFile::getInstances($model,'file');
if($model->validate()){
foreach($files as $file)
$file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'dir' => $dir,
));
}
}
model:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return [
['file', 'file', 'types'=>'jpg'],
];
}
}
view:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form- data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, "[0]file")?>
<?php echo CHtml::activeFileField($model, "[1]file")?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
help me, please
You should fix form enctype, use multipart/form-data instead of multipart/form- data.
You could use CMultiFileUpload
controller:
$images = CUploadedFile::getInstancesByName('image');
foreach ($images as $image => $pic) {
}
view:
$this->widget('CMultiFileUpload', array(
'name' => 'image',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
));
Add to model 'maxFiles' param, if you need validation to work properly for multifiles upload.
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg,gif,png', 'maxSize'=>'204800', 'allowEmpty'=>true, 'maxFiles'=>4),
);
}
Hi I've created a file upload form, it all works perfectly apart from when I press submit it does not re-direct me to the Uploads/add.ctp, but it does save the file to the directory and on to the database.In fact if I point the re-direct to uploads/browse it still does not take me to uploads/browse.
This is my controller
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else{
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
and this is my form
<div class="maincontent">
<?php echo $this->Form->create('Upload', array('type' => 'file', 'class'=>'uploadfrm'));?>
<fieldset class='registerf'>
<legend class='registerf2'>Upload a Video</legend>
<?php
echo 'Upload your video content here, there is no size limit however it is <b>.mp4</b> file format only.';
echo '<br/>';
echo '<br/>';
echo $this->Form->input('name', array('between'=>'<br />', 'class'=>'input'));
echo $this->Form->input('eventname', array('between'=>'<br />'));
echo $this->Form->input('description', array('between'=>'<br />', 'rows'=> '7', 'cols'=> '60'));
echo $this->Form->hidden('userid', array('id' => 'user_id','value' => $auth['id']));
echo $this->Form->hidden('username', array('id' => 'username', 'value' => $auth['username']));
echo $this->Form->input('file', array('type' => 'file'));
echo "<br/>"
?>
<?php echo $this->Form->end(__('Submit', true));?>
</fieldset>
<?php
class UploadsController extends AppController {
public $name = 'Uploads';
public $helpers = array('Js');
// Users memeber area, is User logged in…
public $components = array(
'Session',
'RequestHandler',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'uploads', 'action'=>'browse'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"Members Area Only, Please Login…",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
// regular user can access the file uploads area
if (isset($user['role']) && $user['role'] === 'regular') {
return true;
}
// Default deny
return false;
}
function index() {
$this->set('users', $this->Upload->find('all'));
}
// Handling File Upload Function and updating uploads database
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->redirect(array('controller' => 'Uploads', 'action' => 'add'));
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
} }else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
function browse () {
// Find all in uploads database and paginates
$this->paginate = array(
'limit' => 5 ,
'order' => array(
'name' => 'asc'
)
);
$data = $this->paginate('Upload');
$this->set(compact('data'));
}
function recentuploads () {
$uploads = $this->Upload->find('all',
array('limit' =>7,
'order' =>
array('Upload.date_uploaded' => 'desc')));
if(isset($this->params['requested'])) {
return $uploads;
}
$this->set('uploads', $uploads);
}
function watch ($id = null){
$this->set('isAjax', $this->RequestHandler->isAjax());
// Read Uploads Table to watch video
$this->Upload->id = $id;
$this->set('uploads', $this->Upload->read());
// Load Posts Model for comments related to video
$this->loadModel('Post');
$this->paginate = array(
'conditions' => array(
'uploadid' => $id),
'limit' => 4
);
$data = $this->paginate('Post');
$this->set(compact('data'));
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
}
?>
Any suggestions?
This add function is in your UploadsController, correct? And you want it to redirect to uploads/browse?
In your UploadsController, what is $name set to?
<?php
class UploadsController extends AppController {
public $name = ?; // What is this variable set to?
}
By Cake's Inflector, when you specify controllers in a redirect, it should be lowercase:
$this->redirect(array('controller' => 'uploads', 'action' => 'browse'));
Or if the action you direct from and the action you want to direct to are in the same controller, you do not even need to specify the controller. For example if you submit the form from UploadsController add() and you want to redirect to browse():
$this->redirect(array('action' => 'browse'));
Try that and see if it helps.
Also note that you are calling $this->Upload->save($this->data) twice in your add function.
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
Specifically, here:
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
...
When you call it in the if condition, it still saves the data to the database. It is fine to remove the second one.
If I add the following line in the function add
$this->render();
everything works perfectly, I'm struggling for the life of me to work out why I have to render the view if surely all other views are rendered by default.
But anyway got it working!
Hope this helps others :)