2015-06-07 47 views
0

我使用yii和php 5.5.3創建了上傳文件的表單。下面是我在控制器代碼:錯誤500在上傳文件時從空值創建默認對象

foreach($_FILES['settings']['name'] as $settingName => $value) { 
    $setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName)); 
    $setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']'); 
    if (!empty($setting->image_file)) { 
     $extension = "jpg"; 
     $filename = ""; 
     if (($pos = strrpos($setting->image_file, '.')) !== FALSE) { 
      $extension = substr($setting->image_file, $pos + 1); 
      $filename = substr($setting->image_file, 0, $pos)."_".strtotime("now"); 
     } 
     if (!file_exists("uploads") and !is_dir("uploads")) 
      mkdir("uploads", 0777, TRUE); 

     $setting->image_file->saveAs("uploads/" . $filename.".".$extension, false); 
     $setting->setting_value = "uploads/" . $filename.".".$extension; 
     $setting->save(); 
    } 
} 

image_file在模型中的附加屬性:

array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'), 

這裏是視圖:

<input type="file" name="settings[store_logo]" class="input-small"> 

$setting->image_file->saveAs可以成功上傳的文件,但它也會產生

錯誤500從空值創建默認對象

出了什麼問題?任何幫助將非常感激。

+0

你在哪一行有錯誤500?你能用所有錯誤堆棧更新你的問題嗎? –

回答

0

我想,$ _FILES ['settings'] ['name']在最後一個鍵中有一個空值。 如果您上傳一個或多個文件,它們將按預期進行處理。您的POST-數組中的最後一個值導致空回這裏:

// $setting === null 
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName)) 

這調用拋出的500

$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']'); 

這是我對你的代碼的版本:

<?php 
foreach($_FILES['settings']['name'] as $settingName => $value) { 
    $setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName)); 

    // catch null-return 
    if(!$setting) { 
     echo "can't find stuff at<pre>"; print_r($settingName); echo "</pre>"; 
     continue; 
    } 

    $setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']'); 

    if ($setting->image_file) { 
     $extension = "jpg"; 
     $filename = ""; 
     if (($pos = strrpos($setting->image_file, '.')) !== FALSE) { 
      $extension = substr($setting->image_file, $pos + 1); 
      $filename = substr($setting->image_file, 0, $pos)."_".strtotime("now"); 
     } 
     if (!file_exists("uploads") and !is_dir("uploads")) 
      // dont 0777!  
      mkdir("uploads", 0740, TRUE); 

      $setting->image_file->saveAs("uploads/" . $filename.".".$extension, false); 
      $setting->setting_value = "uploads/" . $filename.".".$extension; 
      $setting->save(); 
    } 
} 
?> 
相關問題