【问题标题】:How to upload only pdf type file in Yii framework using php如何使用 php 在 Yii 框架中仅上传 pdf 类型的文件
【发布时间】:2015-12-06 10:07:07
【问题描述】:

我尝试使用 CMultifileUpload 小部件上传 pdf 类型的文件。这是我的表单代码:

<div class="row" id="file_upload" style="margin-left:20%; margin-bottom:2%;">
         <?php
            $this->widget('CMultiFileUpload',array(
                'name'        => 'files',
                'accept'      => 'pdf',
                'max'         => 1,
                'htmlOptions' => array('size' => 25),
            ));             
            echo CHtml::htmlButton('Upload',array(
            'onclick'=>'javascript: send();', // on submit call JS send() function
            'id'=> 'post-submit-btn', // button id 'newcreate'
            'class'=>'btn btn-primary',
        ));
        ?>

    </div>  

它上传所有类型的文件。但我只想使用这个小部件上传 pdf 类型的文件。我该怎么做?谁能帮助我提供代码示例。

【问题讨论】:

  • 显示服务器端允许的类型。 (你的示范规则)
  • 我该怎么做?可以更具体地告诉我..谢谢@scaisEdge
  • 嗨@ineersa 您提供的链接不起作用...浏览器无法加载链接...我尝试了几次不同的浏览器(chrom、firefox、Opera、Safari).. .你能给我另一个链接吗...
  • 显示与该视图相关的模型代码..

标签: javascript php html yii


【解决方案1】:

_form.php文件内部视图中:

$this->widget('CMultiFileUpload',[
       'model' => $model,
       'attribute' => 'pdf_file',
       'accept' => 'pdf',
       'file' => 'PDF file label',
       'max' => 1, 
       'remove' => 'Remove file',
       'htmlOptions' => ['accept' => 'application/pdf'],
       'denied' => 'ERROR. Incorrect format.', 
       'duplicate' => 'ERROR. Duplicated file'
  ]);

Controller.php 文件中(例如create 操作):

public function actionCreate(){
    $model = new FooModel;
    $this->performAjaxValidation($model);
    if(isset($_POST['FooModel'])){
      $model->attributes = $_POST['FooModel'];
      try{
        $pdf_files = CUploadedFile::getInstancesByName('FooModel');
        if (count($pdf_files) > 0) {
          foreach ($pdf_files as $file) {
            /*
             * $file->name: original name
             * $file->tempName: name in /temp
             * $file->type: e.g. image/png
             * $file->size: size/1024 => kbs
             * $file->error: 0 = no error
             * $file->extensionName
             */
            if (!$f->getHasError()) {
              if(strtolower($f->getExtensionName()) == 'pdf'){
                // do things with file
              }
              else{
                // set errors
                $model->setError('pdf_file', 'Incorrect format');
              }
            }else{
              echo 'Level file error';
            }
          }// foreach
        }// if files
      }
      catch(CDbException $e){
        throw new CHttpException(400, 'Some error');
      }
      catch(Exception $e){
        throw new CHttpException($e->getCode(), $e->getMessage());
      }
    }// if post
    $this->render('create', ['model' => $model]);
  }

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2015-01-02
    • 2013-01-29
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多