2017-06-29 54 views
1

下面的代碼只需上傳一個文件代替幾個文件。 任何想法,如何解決這個問題? 這裏是我的模型:如何使用Yii2上傳多個文件

<?php 
 

 
//Code programmed by Thomas Kipp 
 
//Change it, learn it, do as u please! 
 
///path:/models/ 
 

 
namespace frontend\models; 
 

 
use Yii; 
 
use yii\base\Model; 
 

 
class myScriptForm extends Model{ // A new Class programmed by Thomas Kipp 
 

 
... 
 
    public $avatar; 
 
... 
 

 
    public function rules() { 
 
     $avatar=array(); 
 
     return [ 
 
      ['avatar[]','file']] 
 
    } 
 

 
} 
 

 
//End of class 
 
?>

這裏是我的SiteController的方法:

public function actionScript() { //A new method, programmed by Thomas Kipp 
 
     $model = new myScriptForm(); 
 
     if ($model->load(Yii::$app->request->post()) && $model->validate()) { 
 

 
      $model->avatar = UploadedFile::getInstances($model, 'avatar[]'); 
 
      if ($model->avatar) { 
 
       echo "<font size='4'><br><center>File <font color='red'> " 
 
       . "$model->avatar<font color='black'> successfully uploaded." 
 
       . "<br>It's available in folder 'uploadedfiles' </font></font color></center>"; 
 
       $model->avatar->saveAs(Yii::getAlias('@uploadedfilesdir/' . $model->avatar->baseName . '.' . $model->avatar->extension)); 
 
      } else 
 
       echo"<font size='4'><br><center>No Upload-file selected.<br>" 
 
       . "Nothing moved into folder 'uploadedfiles' </font></center>"; 
 
      return $this->render('myScript', ['model' => $model]); 
 
     } 
 
     else { 
 
      return $this->render('myScript_Formular', ['model' => $model]); 
 
     } 
 
    }
而我的表現公式,這是不上傳多個文件:

<?= 
$form->field($model,'avatar[]')->widget(FileInput::classname(), ['options' => ['accept' => 'image/*', 'multiple' => true],]) 
?> 

回答

1

首先,如果你在控制器中有類似echo (...)的東西 - 你做錯了什麼。

在你的代碼中你不會對上傳的文件做任何foreach,所以它只保存一個。

Yii2 - Uploading Multiple Files - 在這裏你有充分的指導如何上傳多個文件,結合實例等

0

下面的代碼工作對我來說,希望這會幫助你,

查看文件=>

<?= $form->field($model, 'image_files[]')->fileInput(['multiple' => true,'accept' => 'image/*']) ?> 

控制器=>

$imagefiles = UploadedFile::getInstances($model, 'image_files'); 
$model->image_files = (string)count($imagefiles); 

if (!is_null($imagefiles)) { 
    $dirpath = dirname(getcwd()); 
    foreach ($imagefiles as $file) { 
     $productimage = new ProductImages(); 
     $productimage->image_name = '/admin/uploads/'.$file->baseName.'.'.$file->extension; 
     $productimage->product_id = $model->id; 
     if ($productimage->save()) { 
      $file->saveAs($dirpath . '/admin/uploads/' . $file->baseName . '.' . $file->extension); 
     } 
    } 
}