普通网友 2012-01-17 02:31
浏览 19

用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.

  • 写回答

4条回答 默认 最新

  • elliott.david 2012-01-17 03:31
    关注

    Use CHtml::ajaxSubmitButton() instead. That's the correct way to perform ajax submission. Check the documentation here: http://www.yiiframework.com/doc/api/1.1/CHtml/#ajaxSubmitButton-detail instead

    评论

报告相同问题?

悬赏问题

  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?