我尝试使用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类型的文件。我该怎么办?有人可以帮助我提供代码示例。
在_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]);
}