Showing posts with label upload. Show all posts
Showing posts with label upload. Show all posts

Sunday, April 21, 2013

Yii upload image or file to server

Model Image:
<?php
class Image extends CActiveRecord
{
    public $uploaded_owner_img;
  
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    public function tableName()
    {
        return 'table_name';
    }
    
    public function rules()
    {
        return array(
            array('owner_img', 'file', 'allowEmpty'=>true,'types'=>'jpg','maxSize'=>1024*1024*1, 'tooLarge'=>'Image must be less than�1MB'),
            array('owner_name, owner_img', 'required'),
            array('owner_name', 'unique'),
            array('owner_name', 'length', 'max'=>20, 'encoding'=>'utf-8'),
            array('owner_name', 'safe', 'on'=>'search'),
        );
    }
    
    public function attributeLabels()
    {
        return array(
            'owner_img' => 'Select image.',
            'owner_name' => 'Name'
        );
    }
    
    protected function beforeSave() {
        if (parent::beforeSave ()) {
            if ($this->isNewRecord) {
                $this->created = date('Ymd');
            }
            return true;
        }else {
            return false;
        }
    }
}
Controller ImageController.php
<?php
class ImageController extends Controller
{
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            )
        );
    }
        
    public function actionCreate()
    {
        $model=new Image;
        //AJAX validation is needed
        $this->performAjaxValidation($model);
        if(isset($_POST['Image'])) {
            $model->attributes=$_POST['Image'];
            if (@!empty($_FILES['Image']['name']['owner_img'])){
                $model->owner_img = time().".jpg";
                if ($model->validate(array('owner_img'))){
                    $model->uploaded_owner_img = CUploadedFile::getInstance($model, 'owner_img');
                    $model->uploaded_owner_img->saveAs(Yii::app()->basePath.'/'.$model->owner_img);
                    
                    if($model->save()){
                        echo "Model saved"; die(0);
                    }
                }
            }
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }
    
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='map-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
View file
<?php
$this->breadcrumbs=array(
    "image/create"
);

$this->menu=array(
);
?>

<h1>Image Upload</h1>

<div class="form">

<?php 
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'map-form',
    'enableAjaxValidation'=>false,
    'htmlOptions' =>array('enctype'=>"multipart/form-data" ),
    'enableAjaxValidation' => false,
    'enableClientValidation'=>true,
    'clientOptions'=>array('validateOnSubmit'=>true)
)); 
?>

<p class="note">Mark <span class="required">*</span> are required.</p>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo $form->labelEx($model,'owner_name'); ?>
    <?php echo $form->textField($model,'owner_name',array('size'=>32,'maxlength'=>20)); ?>
    <?php echo $form->error($model,'owner_name'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'owner_img'); ?>
    <?php echo $form->fileField($model,'owner_img'); ?>
    <?php echo $form->error($model,'owner_img'); ?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>

<?php $this->endWidget(); ?>
</div>

Friday, February 1, 2013

get file size by jquery before upload

You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {

  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);

});
As it is a part of the HTML5 specification, it will only work for modern browsers (and IE is not one of them).

Sunday, May 20, 2012

Upload file to server using ajax and php

Include jquery.form.js and jquery.min.js

<script type="text/javascript" src="/js/jquery.form.js"></script>
<script type="text/javascript" src="/js/jquery.min.js"></script>

jQuery("#contact-form").ajaxForm({
    beforeSubmit: function() {
        jQuery.showBackgroundWorkingState();
    },
    success: function(data) {
        /*console.log(data);*/
        try {
            if(data == CONSTANT_JS_SUCCESS_CODE) {

            } else {
                jQuery.showWarning("Error uploading file, please try again later.");       
            }
        } catch ( ex ) {
            jQuery.showWarning("Error uploading file, please try again later.");
        }
        jQuery.hideBackgroundWorkingState();
    },
    error: function() {
        jQuery.showWarning("Error uploading file, please try again later.");
        jQuery.hideBackgroundWorkingState();
    }
}).submit(); 
 
File save using php script:

<?php
$name = $_FILES['photoimg']['name'];
list($txt, $ext) = explode(".", $name);
$tmp = $_FILES['photoimg']['tmp_name'];
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageLocation = $docRoot . "/app/webroot/img/";
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
if(move_uploaded_file($tmp, $imageLocation.$actual_image_name)) {
    die("1");
}
die("0"); 
?>