用Ajax调用Yii文件上传?

Hello I'm doing file upload with Yii. I have implemented this way and it works very nice:

View:

echo CHtml::form($this->createUrl('uploadreport'), 'post', array('enctype'=>'multipart/form-data'));
<div id="div_upload" class="row" style="display:none">
    <?php
    $this->widget('CMultiFileUpload',array(
        'name'        => 'files',
        'accept'      => 'doc|docx',
        'max'         => 1,
        'htmlOptions' => array('size' => 25),
    ));

    echo CHtml::submitButton('Upload');
    ?>
</div>

Controller:

if (isset($_FILES['files'])) {
    $tmp_name = $_FILES['files']['tmp_name'][0];
    $filename = $_FILES['files']['name'][0];
    $new_url = '/home/ivan/reports/'.$filename;

    // Upload file
    move_uploaded_file($tmp_name, $new_url);

    $calc_id = $_POST['calc_id'];

    // Check if there is a previous report
    $report = Report::model()->findByAttributes(array('calc_id'=>$calc_id));
    if (isset($report)) {
        // If there is a previous report, delete it
        $qtxt = "DELETE FROM `tbl_reports` WHERE `calc_id` LIKE '$calc_id';";
        $exec = Yii::app()->db->createCommand($qtxt)->execute();
    }

    // Insert the new report
    $rep_add = new Report;
    $rep_add->calc_id = $calc_id;
    $rep_add->report_url = $new_url;
    $rep_add->save();
}

As you can see in my view I am using CHtml::submitButton. But I would like to use this instead:

echo CHtml::button(
    'Upload Report', array(
        'ajax'    => array(
            'type' => 'POST',
            'url'  => CController::createUrl('Calculator/uploadReport'),
        )
    )
);

But if I use the above, then in my controller $_FILES['files'] comes empty or if I try CUploadedFile::getInstance(); it returns an empty string.

I want to use ajax because I don't want to render any other view I want the user to remain in the current view after he/she uploads the file. How can I use Ajax or how can I stop the refreshing of the current view when I use CHtml::submitButton('Upload');

Any hints/help appreciated.

查看全部
weixin_33729196
weixin_33729196
2012/01/17 02:31
  • file-upload
  • reload
  • yii
  • ajax
  • 点赞
  • 收藏
  • 回答
    私信

4个回复